编程新手...我正在尝试了解 JavaScript 中的对象继承。
我收到以下代码的错误。它说:
TypeError: Cannot find function getName in object [object Object]
__proto__
(又名“dunder proto”)在应用程序脚本中不起作用吗?如果没有它,如何将继承设置为除默认“对象”之外的其他对象?
function onPlay(){
//create an employee constructor
function Emp(last, first){
this.first = first;
this.last = last;
this.getName = function() {return(this.first+this.last);}
}
//create an employee
var emp1 = new Emp("Halpert", "Jim");
//log the employee's name
Logger.log(emp1.getName());
//create a manager constructor
function Mgr(){
this.salary = 100,000;
}
//managers are also employees
Mgr.__proto__ = Emp.prototype;
//create a manager
var mgr1 = new Mgr("Scott", "Michael");
//log the manager's name
Logger.log(mgr1.getName());
}
最佳答案
而不是:
Mgr.__proto__ = Emp.prototype;
您可能想要:
Mgr.prototype = Object.create(Emp);
__proto__
属性用于改变原型(prototype),并不一定在所有 JavaScript 引擎中都可用。要为自定义对象构造函数设置原型(prototype),您需要将构造函数上的 prototype
对象设置为基类的实例(Object.create
不调用父构造函数是不必要的)。
关于javascript - Google 应用程序脚本中的 __proto__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41255127/