这里需要注意下,JavaScript 更改方法的 prototype 属性对应的值是一个对象不是一个方法。
- 通过 Object.create
function foo() {
this.name1 = 1;
}
foo.prototype.init = function () {
console.log("foo");
}
function a() {
}
a.prototype.init = function () {
console.log("a");
}
function b() { }
b.prototype = Object.create(a.prototype); // 更改 prototype 的指向
b.prototype.init(); // a
Object.setPrototypeOf(b.prototype, foo.prototype); // 更改 prototype 的指向
b.prototype.init(); // foo
- Object.setPrototypeOf
function foo() {
this.name1 = 1;
}
foo.prototype.init = function () {
console.log("foo");
}
function a() {
}
a.prototype.init = function () {
console.log("a");
}
function b() { }
b.prototype = Object.create(a.prototype); // 更改 prototype 的指向
b.prototype.init(); // a
Object.setPrototypeOf(b.prototype, foo.prototype); // 更改 prototype 的指向
b.prototype.init(); // foo
- 通过 new 对象的方式更改 prototype
function a() {
this.age = 12
}
a.prototype.init = () => {
console.log("a");
}
let b = new a();
console.log(b.age);
b.init() // a
function c() { }
c.prototype = b;
c.prototype.init() // a