构造函数
构造函数和普通函数形式一样,区别在于使用的方式。
function Animal(name) {
this.name = name;
this.subname = name;
this.arr = [1, 2, 3];
this.eat = '吃肉';
}
Animal.prototype.address = {
location: '山里'
}
let mouse = new Animal('老鼠');
let tiger = new Animal('老虎');
通过 new 操作符实例化一个对象,构造函数中的 this 会指向这个新创建的对象,并且单独为其创建属性。还会将这个对象的 proto 属性指向构造函数的原型对象。
proto属性
实例化的对象有一个 proto 属性执行构造函数的原型对象。当无法找到实例对象上的属性时,会去原型对象中去找。
console.log(mouse.arr === tiger.arr);//false
console.log(mouse.address === tiger.address);//true
console.log(mouse.__proto__ === Animal.prototype);//true
console.log(tiger.__proto__ === Animal.prototype);//true
constructor
实例化的对象会有一个 constructor 属性指向构造函数。
console.group(mouse.constructor === Animal);//true
实现继承
call + setPrototypeOf
通过父类上的 call 方法给父类传参,然后通过 proto 属性或者通过 setPrototypeOf 方法将子类的原型指向父类的原型对象。
function Monkey(name) {
this.name = name;
this.age = 10;
Animal.call(this, ...arguments);
}
Monkey.prototype.__proto__ = Animal.prototype;
// 等同于
//Object.setPrototypeOf(Monkey.prototype, Animal.prototype);
const m1 = new Monkey();
console.log(m1.address); //{ location: '山里' }
console.log(m1.eat);//吃肉
console.log(m1.subname);//猴子
console.log(m1.constructor)//[Function: Monkey]
call + Object.create
同样通过 call 给父类传参,然后使用create方法将Monkey的原型对象指向 以Animal的原型对象为原型的新对象,但是需要注意的是需要将构造函数指向Monkey,不然指向的就是 Animal。
function Monkey(name) {
this.name = name;
this.age = 10;
Animal.call(this, ...arguments);
}
Monkey.prototype = Object.create(Animal.prototype, { constructor: { value: Monkey } });
const m1 = new Monkey('猴子');
console.log(m1.address);// { location: '山里' }
console.log(m1.eat);//吃肉
console.log(m1.subname);//猴子*/
console.log(m1.constructor);//[Function: Monkey]
原型继承
不太常用,一样的用call,同时也需要用修改Object.defineProperty 修改实例 constructor,很是麻烦,每次都要修改。
function Monkey(name) {
this.name = name;
this.age = 10;
Animal.call(this,...arguments)
}
Monkey.prototype = new Animal();
const m1 = new Monkey('猴子');
Object.defineProperty(m1, 'constructor', {
value:Monkey
})
console.log(m1.address);// { location: '山里' }
console.log(m1.eat);//吃肉
console.log(m1.subname);//猴子
console.log(m1.constructor);//[Function: Monkey]
拷贝继承
更加鸡肋。。。仅适用用特殊场合。