2017-08-06 62 views
0

混亂在仔細檢查下面的教程代碼JavaScript的原鏈接在此

Animal = function(name) {this.name = name} 
Animal.prototype.eats = function(){ 
     return this.name + ' is eating' 
} 

Chordate = function(name){Animal.call(this,name)} 

我明白我的問題是如何call作品(基本上,在這種情況下,這成爲this)......但是,如何做一個用這個? 我很抱歉,我理解原型是如何工作的。但是,真的,我不明白,一旦你設置Chordate如上所述..人們如何使用它? 這是如何有用?或者你現在如何指定this? 有人可以請示例解釋嗎?

+0

[MDN(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call)有一些很好的例子當你可能想要使用這個。 – Lavios

+1

Youre missing Chordate.prototype = Object.create(Animal.prototype) –

+0

現在讀取MDN ..所以新的Chordate('無論這個如何',arg) – user3502374

回答

1

創建一個鏈接到Animal的原型方法:

Chordate.prototype = Object.create(Animal.prototype) 

然後new起來:

var c = new Chordate('my name'); 

c.eats(); 

Animal.call(this,name)就像撥打電話到基本構造。它執行Animal構造函數並傳遞name,但使用正確的this背景:

Animal = function(name) { 
    // "this" will be your Chordate instance 
    this.name = name 
} 
+0

這有助於我理解這一點。謝謝 – user3502374

0

讓我們想象的youre構建動物:

new Animal(); 

和施工期間,它吸取了新的動物到畫布。構造函數如下所示:

function Animal(){ 
    canvas.draw(this.x,this.y,this.image); 
    } 

現在你已經有了一隻老虎。如果它被修建,老虎應該咆哮。

function Tiger(){ 
    this.roar(); 
} 

現在呢?它的動物是如此加入畫布的嗎?不可以。由於js繼承系統,您需要手動執行此操作。所以,當老虎被構建,還需要構建它作爲動物:

Animal.call(this); 

這甚至與新的類語法簡單:

class Animal{ 
    constructor(){ 
    this.draw(this.x,this.y,this.image); 
    } 
} 

class Tiger extends Animal{ 
    constructor(){ 
    this.roar(); 
    super()//construct Animal 
    } 
} 
0

這只是意味着是一個加法到其他答案,並且對於評論太長了。

也許它可以幫助你明白什麼是new操作實際上做:

var newInstance = new ConstructorFunction(arg1, arg2); 
  1. 創建一個新的對象。此對象的原型是ConstructorFunction.prototype
var newInstance = Object.create(ConstructorFunction.prototype); 
  • 調用ConstructorFunction與新創建的對象:
  • ConstructorFunction.call(newInstance, arg1, arg2); 
    

    如果來自另一個ConstructorFunction繼承「類「,它必須調用它的超級構造函數。這就是下面的代碼做什麼:

    function Parent() { 
        // this === newInstance 
    } 
    
    function Child() { 
        // this === newInstance 
        Parent.call(this); // call the super constructor 
    } 
    
    Child.prototype = Object.create(Parent.prototype); 
    
    var newInstance = new Child(); 
    // or: 
    var newInstance = Object.create(Child.prototype); 
    Child.call(newInstance); // call the constructor, which calls the super constructor 
    
    +0

    真的很喜歡這個.. HOwever,你可以創建沒有ConstructorFunction的第一步嗎?它可以是Object.create(Object.prototype)?我需要從頭開始,而不必依賴以前的任何東西來理解這一點。可以這樣嗎? – user3502374

    +0

    如果它是'Object.create(Object.prototype)',那麼你將不會從'ConstructorFunction.prototype'獲得方法。當然,你可以做到這一點,但我不認爲這就是你想要的。這不是「新」運營商的工作方式。 – PeterMader

    +0

    真的很喜歡這個角度..但讓我回到這..現在閱讀更多關於這個話題 – user3502374