0

我想了解Javascript的原型。我知道我可以将功能添加到原型Calculator.prototype.calculate = function(){};,但是当我尝试设置一个新的原型时,一切都崩溃了。 calc.prototype返回undefined。我的问题是为什么我们不能设置一个新的对象作为原型?如何将方法添加到批量原型而不是逐个添加?如何设置函数的原型

var calc = new Calculator(); 

function Calculator(){ 
    this.array = []; 
    this.results = 0; 
} 

Calculator.prototype = { 

    calculate: function(){ 
     try{ 
     results = eval(this.array.join('')); 
     this.array = [results]; 
     return results; 
     } 
     catch(error){ 
      alert('Wrong arguments provided'); 
      return this.array.join(''); 
     } 
    }, 

    isNumber: function(str){ 
     return !isNaN(parseFloat(str)) && isFinite(str); 
    }, 

    addToOperationsArray: function(str){ 
     if (this.array.length <= 0 && !this.isNumber(str)){ // Don't add operand before any number. 
      return; 
     } 

     this.array.push(str); 

    }, 
    clearEverything: function(){ 
     this.array = []; 
    } 
}; 
+0

您不能将新对象设置为原型,因为现有原型不仅仅是一个空对象。它包括,例如,非常必要的构造函数。你需要扩展现有的原型;有很多方法可以做到这一点,其中之一是使用新的[Object.assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)方法 – Hamms

+0

一切如何分崩离析?你是否检查过“calc .__ proto__”,你会发现它在那里。很明显,你不会使用它 - 但它是在那里告诉你它确实存在。 –

+0

是的,它仍然指向Calculator.prototype,它是一个具有构造函数属性的对象,它具有包含所有这些方法的原型,但由于无法调用它们而无用。它增加了更多的混淆,因为以前我虽然断链,但现在我看到这些函数在原型中,这是我们称之为JavaScript的黑洞中的某个地方。 –

回答

1

你最有可能试图分配之前访问(新)的原型对象。您可以使用Calculator构造函数,因为函数声明受制于hoisting。分配不是。

在进行这些更改之前,您构建的对象的原型将成为在调用时原型的对象。

// use the default prototype 
var test1 = new Test(); 

// a new prototype is assigned 
// objects created from this point will use it 
Test.prototype = { 
    report: function(){ alert('jah live children yea'); } 
}; 
var test2 = new Test(); 

test1.report();  // Uncaught TypeError: test1.report is not a function 
test2.report();  // alerts 


function Test(){} // hoisted so you can use it before this line 

注意,您可以使用原型属性与创建被加入到原型之前他们,如果原型对象本身没有改变,而只是扩展的对象。

只有在功能分配前不进行呼叫才是重要的。

var test1 = new Test(); 

test1.report();  // Uncaught TypeError: test1.report is not a function 

// extend the prototype object 
// the added property is accessible by existing objects 
Test.prototype.report = function(){ 
    alert('jah live children yea'); 
}; 

test1.report();  // alerts 


function Test(){} 
+1

看哪。你解决了这个谜团。 –