原型:
<script>
// 构造函数
function Star(uname, age){
this.uname = uname;
this.age = age;
this.dance = function(){
console.log("跳舞");
}
}
Star.prototype.sing = function(){
console.log('我会唱歌');
}
var ldh = new Star('刘德华', 18);
var zxy = new Star('张学友', 19);
console.log(ldh.dance === zxy.dance);
// false
console.log(ldh.sing === zxy.sing);
// true
// 定义是放在构造函数里面,构造方法在属性里面比较占据内存,一般把原型方法放在原型对象上面,
</script>
对象原型
<script>
// Star的构造方法
// prototype是为函数添加方法
function Star(uname, age) {
this.uname = uname;
this.age = age;
}
Star.prototype.sing = function() {
console.log('我会唱歌');
}
var ldh = new Star('刘德华', 18);
var zxy = new Star('张学友', 19);
// 属性的__proto__ 指向的是方法原型链上的方法
ldh.sing();
console.log(ldh); // 对象身上系统自己添加一个 __proto__ 指向我们构造函数的原型对象 prototype
console.log(ldh.__proto__ === Star.prototype);
// 方法的查找规则: 首先先看ldh 对象身上是否有 sing 方法,如果有就执行这个对象上的sing
// 如果么有sing 这个方法,因为有__proto__ 的存在,就去构造函数原型对象prototype身上去查找sing这个方法
// 也就是说Star构造函数的prototype 和 对象上的 ldh 的__proto__ 指向是同一个位置
</script>
原型constructor
<script>
function Star(uname, age){
this.uname = uname;
this.age = age;
}
Star.prototype = {
// 可以利用 Star.prototype = {} 修改constructor属性,但必须把constructor指向方法
constructor: Star,
sing: function () {
console.log('我会唱歌');
},
movie: function () {
console.log('我会看电影');
},
}
var ldh = new Star('刘德华', 18)
console.log(Star);
console.log(Star.prototype);
// constructor相当于查看函数的初始构造函数
console.log(Star.prototype.constructor);
console.log(ldh.__proto__.constructor);
</script>
原型链
<script>
function Star(uname, age) {
this.uname = uname;
this.age = age;
}
Star.prototype.sing = function() {
console.log('我会唱歌');
}
var ldh = new Star('刘德华', 18);
console.log(typeof ldh);
// 1. 只要是对象就有__proto__ 原型, 指向原型对象
console.log(Star.prototype);
console.log(ldh.__proto__);
// 首先 Star.prototype,是找Star的原型链以及里面的方法
// ldh.__proto__ 是对象ldh的原型链,由于新建一个对象出来,原型链也是Star.
// js万物皆对象,所以Star也是继承Object的对象.所以Star.prototype.__proto__的原型是Object
// 最终Object指向null
console.log(Star.prototype.__proto__ );
console.log(Star.prototype.__proto__ === Object.prototype);
// 2.我们Star原型对象里面的__proto__原型指向的是 Object.prototype
console.log(Object.prototype.__proto__);
// 3. 我们Object.prototype原型对象里面的__proto__原型 指向为 null
</script>
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/webdev/279037.html