2011-05-03 139 views
4

爲什麼版本2在下面的代碼中不會產生與版本1相同的結果?Javascript繼承問題

function person(name) { 
    this.name = name; 
} 
function student(id, name) { 
    this.id = id; 
    // Version 1 
    //this.inherit_from_person = person; 
    //this.inherit_from_person(name); 
    // Version 2 
    person(name); 
} 
s = new student(5, 'Misha'); 
document.write(s.name); // Version 1 => Misha 
         // Version 2 => undefined 

Live demo here.

回答

6

當你調用person(name)它被稱爲與this綁定到全局對象,所以這只是設置window.name = "Misha"。您希望person.call(this, name)將其明確地綁定到正確的this

3

它看起來像我正在試圖實現原型繼承。下面是一個典型的例子,雖然用處不大。在JavaScript中不需要複雜的繼承,通常只需要一個實例。如果需要多個實例,則模塊模式可用於共享方法和屬性的閉包,也可用於提供私有和有成員的成員。

// Person is the "base class" 
function Person(name) { 
    this.setName(name); 
} 

// Use setters and getters so properties are 
// added appropriately. 
Person.prototype.setName = function(name) { 
    this.name = name; 
} 

// Add Person methods 
Person.prototype.getName = function() { 
    return this.name; 
} 

// Student inherits from Person and also has 
// its own methods 
function Student(name, id) { 
    this.setId(id); 
    this.setName(name); 
} 

// To inherit from Person, Student.prototype should 
// be an instance of Person 
Student.prototype = new Person(); 

// Add Student methods 
Student.prototype.setId = function(id) { 
    this.id = id; 
} 
Student.prototype.getId = function() { 
    return this.id; 
} 

var p0 = new Student('Sally', '1234'); 
var p1 = new Person('James'); 

alert('p0\'s id is ' + p0.id + ' and name is: ' + p0.name); 
alert('p1\'s name is: ' + p1.name); 
alert('Is p0 a student? ' + (p0 instanceof Student)); 
alert('Is p1 a student? ' + (p1 instanceof Student)); 

注意,的instanceof運營商並不十分可靠,但在上述情況下正常工作。而且所有的方法和屬性都很容易被公開寫入。

+0

非常感謝你的例子! – 2011-05-03 04:13:13