当我使用构造函数创建我的对象时,下面的代码工作,但是当我做object.Create它没有正确初始化 . functionName is not a function
. 我有两个问题 . 为什么object.create不起作用?
我如何在同一个计算器函数中组织我的代码,以便我可以同时使用new和object.create?
我知道我可以将方法添加到Calculator.prototype并执行Object.create,但我想知道我的代码是否可以在当前结构中更改以允许两者兼而有之?
//var calc = new Calculator();
var calc = Object.create(Calculator);
function Calculator(){
this.array = [];
this.results = 0;
this.calculate = function(){
try{
results = eval(this.array.join(''));
this.array = [results];
return results;
}
catch(error){
alert('Wrong arguments provided');
return this.array.join('');
}
},
this.isNumber = function(str){
return !isNaN(parseFloat(str)) && isFinite(str);
},
this.addToOperationsArray = function(str){
if (this.array.length <= 0 && !this.isNumber(str)){ // Don't add operand before any number.
return;
}
this.array.push(str);
},
this.clearEverything = function(){
this.array = [];
}
}
3 回答
没有Object.create的构造函数调用 .
您可以通过多种方式获得类似的结果 . 看看这些内容是否有助于您:
你想要的是实例化对象,你可以这样做:
Object.create 与 new 一起使用并不反对 . 只是为了使它成为 more clear 关于原型继承和实例化,让's take step back, I' ll为你提供 example :
上面的例子太冗长了吗? (ES2015在这里提供帮助)请注意,这只适用于节点v6及更高版本 .
有点晚了,可能你已经注意到了,但在你的实现中,至少有一个副作用在代码中
Calculator.prototype.constructor
这将指向Object.prototype.constructor
而不是Calculator构造函数,你在做什么是覆盖原型链的每个属性,最佳做法是使用点表示法添加新属性Calculator.prototype.method = () => { // some code }