一道考察 JavaScript 的 Class 知识点的题目,难倒我了,求解

2018 年 11 月 13 日
 nohup

现有一段代码如下:

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();

各位前端大佬,这道题应该如何求解,谢谢!

3069 次点击
所在节点    程序员
15 条回复
zjsxwc
2018 年 11 月 13 日
方法 1: 估计是靠古老的 es5 prototype 吧,不过把 es5 与 es6 混合起来写怕是要被同事打死。

方法 2: 使用面向对象思想,通过组合代替继承也是可行的
azh7138m
2018 年 11 月 13 日
zhzer
2018 年 11 月 13 日
按顺序 call 构造函数,不就完事了?
neko2
2018 年 11 月 13 日
```javascript
function getSonClassByExtends(sonObj,Parent){
// finish the function code and make it work
function son() {}
son.prototype = sonObj;
sonObj.__proto__ = Parent.prototype;
return son;

}
```
msputup
2018 年 11 月 13 日
是我孤陋寡闻了?什么时候有 Son son 的写法了?题目本身不难,就是 prototype 原型链的问题。但是 Son son 什么鬼?
autoxbc
2018 年 11 月 13 日
function getSonClassByExtends(sonObj,Parent){
return function(){
return Object.assign( new Parent() , sonObj );
}
}

如果 work 就行那也不用搞一堆幺蛾子
jmperdev
2018 年 11 月 13 日
function getSonClassByExtends(sonObj,Parent){
var F = function() {
F.prototype = Parent.prototype;
sonObj.prototype = new F();
sonObj.prototype.constructor = sonObj;
}
}
Biwood
2018 年 11 月 13 日
用原型链能达到目的,但是也不是标准的继承,因为你没办法做到 son.constructor === Son 返回 true 吧
mdluo
2018 年 11 月 13 日


与其说是考察原型,不如说是考察 new 关键字
kran
2018 年 11 月 13 日
时代的变化啊,现在很少研究原型链的了
Sparetire
2018 年 11 月 13 日
方法很多,因为没有涉及到 this,你甚至不用真的继承也能输出符合题目要求的结果,你只需要借用这两个方法就好了。。但是借用方法并不一定要继承。不过个人觉得是想考察原型继承和对象继承(其实都是原型继承),所以建议对 sonObj 的处理用 Object.create
carlclone
2018 年 11 月 13 日
连我个后端都知道 prototype。。。
spark
2018 年 11 月 13 日
Son son 是什么鬼……
66beta
2018 年 11 月 13 日
#9 楼正解
告诉考官:class 是不推荐的写法,本来就没有类,装什么类
kiinlam
2018 年 11 月 14 日
Son son 那是 java 的写法了吧。

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

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

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

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

© 2021 V2EX