2012-06-03 14 views
5

Bu, CoffeeScript'in extends anahtar kelimesi tarafından oluşturulan JavaScript kodudur. Prototip zinciri nasıl kurulur?CoffeeScript'in `extends` anahtar kelimesiyle oluşturulan JavaScript kodu nasıl anlayabilirim?

var __hasProp = Object.prototype.hasOwnProperty, 
__extends = function(child, parent) { 
    for (var key in parent) { 
     if (__hasProp.call(parent, key)) child[key] = parent[key]; 
    } 
    function ctor() { this.constructor = child; } 
    ctor.prototype = parent.prototype; 
    child.prototype = new ctor; 
    child.__super__ = parent.prototype; 
    return child; 
}; 
+0

Hangi parçası sana sorun veriyor? –

+0

bu satırı anlamıyor: 'ctor.prototype = parent.prototype; ' – powerboy

+0

Blog gönderim detayı bunu. "ctor" bir * vekil * kurucu olarak adlandırılır. Ebeveynin prototipini kopyaladığınız ayrı bir kurucu. Sadece çocuğun mirasını kurmaya gerek kalmadan, 'child.prototype = new ctor' prototip zincirini kurar. Daha bilinen (ama problemli) kalıtımı ayarlama yolu, child.prototype = new parent' yapmaktır. Yine, blog gönderim, blog yazınızı okuduğum –

cevap

7
var __hasProp = Object.prototype.hasOwnProperty, 
__extends = function(child, parent) { 
    // Copy "static" attributes from the parent constructor to the child constructor 
    for (var key in parent) { 
     if (__hasProp.call(parent, key)) child[key] = parent[key]; 
    } 
    // This is the surrogate constructor, used so you don't need 
    // to instantiate an instance of the parent just to setup the prototype chain 
    // the statement in the surrogate constructor properly attaches 
    // the constructor property to object 
    function ctor() { this.constructor = child; } 
    // Attach the parent's prototype to the surrogate constructor 
    ctor.prototype = parent.prototype; 
    // This is setting up the chain, attaching an instance of a constructor whose 
    // prototype is set to the parent to the prototype property of the child 
    // In naive implementations, this would be child.prototype = new parent(); 
    child.prototype = new ctor; 
    // Allows access to the parent from user code, and used by the `super` keyword 
    child.__super__ = parent.prototype; 
    return child; 
}; 

Bkz http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html (kendi blog yazısı)

+0

OP'nin ilgilendiği bölüm olmadığını biliyorum, ancak bu kodun neden bu __hasProp gibi kullanıldığını biliyor musunuz? Bunun ne anlama geldiğini anladım (eğer if (parent.hasOwnProperty (key)) '... – nnnnnn

+3

Ebeveyn üzerinde bir 'parent.hasOwnProperty' özelliği üzerine yazılsa bile hala çalışır. Bazen "{} .hasOwnProperty.call (parent, key)" olarak yazılmıştır –

+0

Tamam, güzel. Teşekkürler. – nnnnnn

İlgili konular