Object.setPrototypeOf(A.protytype,B.prototype)A.prototype = Object.create(B.prototype)都能达到A.prototype.__proto__ = B.prototype 的效果,一般用于继承
使用第二种A.prototype = Object.create(B.prototype),因为使用了等号赋值,所以首先达成的效果是改变A.prototype使它等于Object.create()返回的新的对象,其次才会达到A.prototype.__proto__ = B.prototype的效果,所以Object.create()会覆盖A.prototype,但是Object.setPrototypeOf()不会有这个副作用。
///使用Object.create()
function Father1() {
this.name = "father1";
}
Father1.prototype.arr = [1, 2];
function Son1() {
this.type = "son1";
}
Son1.prototype.getType = function () {
return "son1 from prototype";
};
Son1.prototype = Object.create(Father1.prototype);
Son1.prototype.constructor = Son1;
let son1 = new Son1();
console.log(son1.arr); //[1,2]
console.log(son1.type); //'son1'
console.log(son1.getType); //undefined 最主要区分
//使用Object.setPrototypeOf()
function Father2() {
this.name = "father2";
}
Father2.prototype.arr = [1, 2];
function Son2() {
this.type = "son2";
}
Son2.prototype.getType = function () {
return "son2 from prototype";
};
Object.setPrototypeOf(Son2.prototype, Father2.prototype);
let son2 = new Son2();
console.log(son2.arr); //[1,2]
console.log(son2.type); //'son2'
console.log(son2.getType); //function(){}
function create(newPrototype){
let NewConstruc = function(){}
NewConstruc.prototype = newPrototype
return new NewConstruc()
}