function object(o) {
function F() {}
F.prototype = o;
return new F();
}
function prototype(child, parent) {
var prototype = object(parent.prototype);
prototype.constructor = child;
child.prototype = prototype;
}
// 当我们使用的时候:
prototype(Child, Parent);
这是比较标准的答案
然后我这么写的话有问题吗?我感觉差不多
function extend(Parent, Child) {
Child.prototype.__proto__ = Parent.prototype;
}
```JavaScript
function inherit(son, father){
let prototypeObj = Object.create(father.prototype);
prototypeObj.constructor = son;
son.prototype = prototypeObj;
}
```
语法没出来 凑活看下吧
不要用__proto__这个
不行,构造函数没指向
ts 它不香吗?
我觉着唯一的区别是:
标准答案那个调用了 prototype 后, child.prototype 上的东西就没了.
楼主的就没问题
function prototype(child, parent) {
Object.setPrototypeOf(child.prototype, parent.prototype);
}
七楼的方法作为 ES6 之后的方法完美复现了标准答案的所有副作用,这边补充一下:
function a(){}
function b(){}
Object.setPrototypeOf(b.prototype, a.prototype)
const c = new b();
c.constructor === b() // true
c instance of b // true
c instance of a // true
---
顺带一提,标准答案的 object 方法可以视为当 Object.creat()不可用的时候的一个简单 polyfill,当然它并没有实现所有的 Object.create,仅仅将主要作用实现了。
Child.prototype.__proto__ = Parent.prototype;
此时 Child 的原型指向构造函数的指针指向 Parent 构造函数而不是 Child
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
Deprecated
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto
Warning: Changing the [[Prototype]] of an object is, by the nature of how modern JavaScript engines optimize property accesses, currently a very slow operation in every browser and JavaScript engine