
现有一段代码如下:
class Parent{ say(){ console.log('that method called from parent method'); } } class Son extends Parent{ sayChild(){ console.log('that method called from son method'); } } Son son = new Son(); son.say(); son.sayChild(); 假设现在你不可以使用 extends 关键字来直接继承父类,只给你一个对象,你应该如何完成以下代码块:
class Parent{ say(){ console.log('that method called from parent method'); } } var sOnObj= { sayChild(){ console.log('that method called from son method'); } } function getSonClassByExtends(sonObj,Parent){ // finish the function code and make it work } var Son = getSonClassByExtends(sonObj,Parent); Son son = new Son(); son.say(); son.sayChild(); 各位前端大佬,这道题应该如何求解,谢谢!
1 zjsxwc 2018-11-13 19:41:27 +08:00 via Android 方法 1: 估计是靠古老的 es5 prototype 吧,不过把 es5 与 es6 混合起来写怕是要被同事打死。 方法 2: 使用面向对象思想,通过组合代替继承也是可行的 |
2 azh7138m 2018-11-13 20:18:42 +08:00 |
3 zhzer 2018-11-13 20:35:19 +08:00 via Android 按顺序 call 构造函数,不就完事了? |
4 neko2 2018-11-13 20:49:28 +08:00 ```Javascript function getSonClassByExtends(sonObj,Parent){ // finish the function code and make it work function son() {} son.prototype = sonObj; sonObj.__proto__ = Parent.prototype; return son; } ``` |
5 msputup 2018-11-13 21:08:58 +08:00 是我孤陋寡闻了?什么时候有 Son son 的写法了?题目本身不难,就是 prototype 原型链的问题。但是 Son son 什么鬼? |
6 autoxbc 2018-11-13 21:34:00 +08:00 function getSonClassByExtends(sonObj,Parent){ return function(){ return Object.assign( new Parent() , sonObj ); } } 如果 work 就行那也不用搞一堆幺蛾子 |
7 jmperdev 2018-11-13 21:50:38 +08:00 function getSonClassByExtends(sonObj,Parent){ var F = function() { F.prototype = Parent.prototype; sonObj.prototype = new F(); sonObj.prototype.cOnstructor= sonObj; } } |
8 Biwood 2018-11-13 21:53:48 +08:00 用原型链能达到目的,但是也不是标准的继承,因为你没办法做到 son.cOnstructor=== Son 返回 true 吧 |
9 mdluo 2018-11-13 22:05:31 +08:00 |
10 kran 2018-11-13 22:10:56 +08:00 via iPhone 时代的变化啊,现在很少研究原型链的了 |
11 Sparetire 2018-11-13 22:12:52 +08:00 via Android 方法很多,因为没有涉及到 this,你甚至不用真的继承也能输出符合题目要求的结果,你只需要借用这两个方法就好了。。但是借用方法并不一定要继承。不过个人觉得是想考察原型继承和对象继承(其实都是原型继承),所以建议对 sonObj 的处理用 Object.create |
12 carlclone 2018-11-13 22:18:02 +08:00 连我个后端都知道 prototype。。。 |
13 spark 2018-11-13 22:21:00 +08:00 via iPhone Son son 是什么鬼…… |
14 66beta 2018-11-13 22:38:18 +08:00 #9 楼正解 告诉考官:class 是不推荐的写法,本来就没有类,装什么类 |
15 kiinlam 2018-11-14 09:27:38 +08:00 Son son 那是 java 的写法了吧。 |