js 寄生组合继承

2020-03-10 15:24:38 +08:00
 johnnyNg

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;
}
2244 次点击
所在节点    JavaScript
10 条回复
godgc
2020-03-10 15:29:41 +08:00
```JavaScript
function inherit(son, father){
let prototypeObj = Object.create(father.prototype);
prototypeObj.constructor = son;
son.prototype = prototypeObj;
}
```
godgc
2020-03-10 15:30:03 +08:00
语法没出来 凑活看下吧
chenliangngng
2020-03-10 18:16:05 +08:00
不要用__proto__这个
Yumwey
2020-03-10 19:49:05 +08:00
不行,构造函数没指向
shujun
2020-03-10 20:08:27 +08:00
ts 它不香吗?
rabbbit
2020-03-10 20:32:21 +08:00
我觉着唯一的区别是:
标准答案那个调用了 prototype 后, child.prototype 上的东西就没了.
楼主的就没问题
zhw2590582
2020-03-10 20:36:50 +08:00
function prototype(child, parent) {
Object.setPrototypeOf(child.prototype, parent.prototype);
}
Zhuzhuchenyan
2020-03-10 20:58:09 +08:00
七楼的方法作为 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,仅仅将主要作用实现了。
ironMan1995
2020-03-10 21:29:09 +08:00
Child.prototype.__proto__ = Parent.prototype;
此时 Child 的原型指向构造函数的指针指向 Parent 构造函数而不是 Child
SoloCompany
2020-03-10 21:32:17 +08:00
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

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/651533

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX