2017-01-03 105 views
0

我想做一個構造函數。然後我試圖使用它的原型並打印「彼得」。但它顯示一個錯誤。打印原型不工作在JS

function main(){ 
 

 
    var func1 = function(){ 
 
\t this.name = "Peter"; 
 
\t this.age = 27; 
 
\t this.class = "10"; 
 
    } 
 

 
    func1.prototype.printName = function(){ 
 
\t console.log(this.name); 
 
    } 
 

 
    return func1; 
 
} 
 

 
var a = main(); 
 

 
a.printName();

+0

https://plnkr.co/edit/jYMbQWbcfZ6Q243Hu1Cf?p=preview –

回答

3

您指定的構造函數func1a,不是實例func1。只有func1的實例有printName方法。在某些時候,您需要撥打new func1()new a()。例如。你可以做return new func1();而不是return func1;

看看下面的簡化示例。

var func1 = function() { 
 
    this.name = "Peter"; 
 
    this.age = 27; 
 
    this.class = "10"; 
 
} 
 

 
func1.prototype.printName = function() { 
 
    console.log(this.name); 
 
} 
 

 
var a = new func1(); 
 

 
a.printName();

我建議閱讀eloquentjavascript.net - The Secret Life of Objects