2011-06-11 98 views
1

我正在閱讀這本關於繼承的JS書,我對每一行都在做什麼感到困惑。如果我的理解是正確的,有人可以告訴我。JavaScript中的繼承

function classA(sColor){ 
    this.color = sColor; 
    this.sayColor = function(){ 
     alert(this.color); 
    }; 
} 

function ClassB(sColor, sName){ 
    this.newMethod = classA; //assigning a reference to a parent class 
    this.newMethod(sColor); //calling the constructor of the parent class 

    //question: so what is 'this' then? from my understanding when we call 'new ClassB('a','b')' 
    //we instantiate a new object and that new object becomes the 'this' in this case. Does this 
    //line mean we are converting the this to classA? 

    delete this.newMethod; //deleting reference to the CONSTRUCTOR of the parent class 

    this.name = sName; 
    this.sayName = function(){ 
     alert(this.name); 
    } 

} 
+2

如果這是你的書給你的繼承模式,我會去買另一本書。例如Crockford的Good Parts。 – Magnar 2011-06-11 19:06:29

+0

我很少在js中使用繼承,但理解'this'很重要。如果你的目標是理解那很酷的事情,但是如果你想了解繼承,那麼它不會被使用。至少繼承是像你在上面那樣使用的。 – William 2011-06-11 19:07:17

+0

這是本書所展示的第一個繼承例子,是的,我試圖瞭解代碼中每個地方的「this」是什麼。 – denniss 2011-06-11 19:09:57

回答

2

How this works

function ClassB(sColor, sName){ 
    this.newMethod = classA; 
    this.newMethod(sColor); 

    delete this.newMethod; 

    this.name = sName; 
    this.sayName = function(){ 
     alert(this.name); 
    } 
} 

是這樣

function ClassB(sColor, sName){ 
    classA.call(this, sColor); 

    this.name = sName; 
    this.sayName = function(){ 
     alert(this.name); 
    } 
} 

var f = new ClassB("green", "boy"); 
f.sayName(); // boy 
f.sayColor(); // green 

你基本上調用classA構造與this對象的一個​​平庸的方式。

JavaScript沒有類,它只是具有操縱對象的對象和函數。您的ClassA功能操縱thisClassB也是如此。

ClassA只是一個操縱對象的函數。在這種情況下,它操縱context對象,即this。所有ClassB正在做的是說

  • 讓ClassA的操縱this
  • 一個名爲name屬性添加到this
  • 添加一個方法叫sayNamethis

獎勵:

有 一個更好的辦法做到OO在JavaScript

// A is a blueprint for an object with a method sayColor 
var A = (function() { 
    var self = Object.create({}); 
    self.sayColor = function() { 
    alert(this.color); 
    }; 
    return self; 
}()); 

// B is a blueprint for an object with methods sayColor and sayName 
var B = (function() { 
    // clone the methods from A 
    var self = Object.create(A); 
    self.sayName = function() { 
    alert(this.name); 
    }; 
    return self; 
}()); 

// clone B and set the properties for name and color 
var b = Object.create(B, { 
    name: { value: "boy" }, 
    color: { value: "green" } 
}); 

/* or use a factory 

var bFactory = function(name, color) { 
    return Object.create(B, { 
    name: { value: name }, 
    color: { value: boy } 
    }); 
} 

b = bFactory("boy", "green"); 

*/ 

b.sayName(); 
b.sayColor(); 

使用Object.create這是ES5所以使用ES5-shim支持舊版瀏覽器。

+0

誰持續引用新實例化的classA實例? – denniss 2011-06-11 19:10:34

+0

不要錯過! – denniss 2011-06-11 19:11:38

+0

@denniss你不會創建classA的新實例,除非你調用'new classA'。你實際上做的是調用'ClassA'函數,並說'ClassB'中的'this'作爲'ClassA'中的'this' – Raynos 2011-06-11 19:11:41