2017-02-17 92 views
1

我是新來的JS,並得到以下問題:調用對象原型的方法

爲什麼這不工作/這是什麼代碼在做什麼?

var Test = {}; 
Test.prop = "test property"; 

Test.Class1 = function() { 
} 

Test.Class1.prototype = { 
    m1: function() { 
     console.log(this.prop); 
    } 
} 

Test.Class1.m1(); 

我這個代碼的理解是:

  1. 創建一個新的名爲對象測試
  2. 添加屬性道具測試
  3. 創建一個新的對象調用Class1 in Test
  4. 添加一個方法M1Class1的
  5. 調用的Class1M1方法測試

回答

1

在JavaScript中,甚至prototy函數的pe屬性是一個對象。在創建一個其原型是您定義的原型的對象之前,Test1.Class1.prototype只是一個常規對象。基本上,它的工作方式相同,下面的代碼片段:

var Test1 = { prototype { m1: function() {} } }; 
// You're trying to call an undefined function! 
Test.m1(); 

// This is fine 
Test1.prototype.m1(); 

在另一方面,當您使用new運營商,您要創建一個新的對象,其原型是一組的構造函數。而這裏開始魔術

var Test1 = function() {}; 
Test1.prototype = { 
    doStuff: function() {} 
}; 

var object1 = new Test1(); 
// This works! 
object1.doStuff(); 

當您訪問的屬性,JavaScript的運行時檢查對象,以找出是否有一個名爲doStuff功能,否則它會尋找它的對象的原型,否則它看起來原型的原型等...

其實new運營商是syntactic sugar。 ECMA腳本5中引入Object.create這使得一切更加清晰:

var Test1 = { 
    doStuff: function() { 
    } 
}; 

// The first parameter of Object.create is 
// the object that's going to be the prototype of 
// Test1 object! 
var object1 = Object.create(Test1); 
// This works too! 
object1.doStuff(); 

也許你應該檢查這個其他Q &答:How does JavaScript .prototype work?

0

prototype只鏈接工程與新的運營商創建的實例。

否則,您將不得不顯式調用原型來訪問該方法。

let testClass = new Test.Class1(); 

testClass.m1(); 

此外,由於您正試圖訪問prop屬性。

Test.Class1.prototype = { 
    m1: function() { 
     console.log(this.prop); 
    } 
} 

調用點是Test.Class1,則prop應該是Test.Class1一部分,而不是Test

+0

不但。怎麼樣'Object.create':D –

0

我改變了事物的名稱,但這應該工作。

var Person = function(){ 
    this.message = "Hello, world!"; 
}; 

Person.prototype = Object.create(Object.prototype); 
Person.prototype.constructor = Person; 

Person.prototype.greet = function(){ 
    console.log(this.message); 
    alert(this.message); 
}; 

var tom = new Person(); 
tom.greet(); 
0

您需要創建原型的一個實例,你能夠使用它的方法之前:

var instance = new Test.Class1(); 
console.log(instance.m1()); 

即使這樣,Test.prop不是實例的一部分,並不會可以訪問到M1

編輯:這是一個工作示例:

var test = function() { 
    this.prop = "A property"; 
} 

test.prototype.m1 = function() { 
    console.log(this.prop); 
} 

var instance = new test(); 
console.log(instance.m1());