2012-06-03 19 views
5

Đây là mã JavaScript được tạo bởi từ khóa extends của CoffeeScript. Làm thế nào các chuỗi nguyên mẫu được thiết lập?Cách hiểu mã JavaScript được tạo bởi từ khóa 'extends` của CoffeeScript

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

Phần nào là cho bạn gặp rắc rối? –

+0

không hiểu dòng này: 'ctor.prototype = parent.prototype; ' – powerboy

+0

Chi tiết bài đăng trên blog của tôi đó. 'ctor' được gọi là hàm tạo * thay thế *. Đó là một hàm tạo riêng biệt mà bạn sao chép nguyên mẫu của phụ huynh. Nó thiết lập chuỗi nguyên mẫu 'child.prototype = new ctor' mà không cần phải gọi hàm tạo của cha mẹ chỉ để thiết lập kế thừa. Cách thiết lập thừa kế hơn (nhưng có vấn đề) là bằng cách thực hiện 'child.prototype = new parent'. Một lần nữa, bài đăng trên blog của tôi đi sâu vào chi tiết về các vấn đề với số –

Trả lời

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; 
}; 

Xem http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html (bài viết trên blog của riêng tôi)

+0

Tôi biết đó không phải là phần mà OP quan tâm, nhưng bạn có biết tại sao mã này sử dụng '__hasProp' như thế không? Tôi không hiểu làm thế nào mà giúp so sánh với nói rằng 'if (parent.hasOwnProperty (key))' ... – nnnnnn

+3

Nó như vậy nó vẫn hoạt động ngay cả khi một tài sản 'parent.hasOwnProperty' đã được ghi đè trên phụ huynh. Đôi khi được viết dưới dạng '{} .hasOwnProperty.call (cha mẹ, khóa)' –

+0

OK, hay. Cảm ơn. – nnnnnn

Các vấn đề liên quan