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; }
![]() | 1 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; } ``` |
![]() | 2 godgc 2020-03-10 15:30:03 +08:00 语法没出来 凑活看下吧 |
3 chenliangngng 2020-03-10 18:16:05 +08:00 ![]() 不要用__proto__这个 |
![]() | 4 Yumwey 2020-03-10 19:49:05 +08:00 ![]() 不行,构造函数没指向 |
5 shujun span class="ago" title="2020-03-10 20:08:27 +08:00">2020-03-10 20:08:27 +08:00 via iPhone ts 它不香吗? |
![]() | 6 rabbbit 2020-03-10 20:32:21 +08:00 ![]() |
![]() | 7 zhw2590582 2020-03-10 20:36:50 +08:00 ![]() function prototype(child, parent) { Object.setPrototypeOf(child.prototype, parent.prototype); } |
![]() | 8 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,仅仅将主要作用实现了。 |
![]() | 9 ironMan1995 2020-03-10 21:29:09 +08:00 ![]() Child.prototype.__proto__ = Parent.prototype; 此时 Child 的原型指向构造函数的指针指向 Parent 构造函数而不是 Child |
![]() | 10 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 |