2010-04-15 83 views
1

var Dog = function(name){ this.name = name; this.sayName(); }如何從構造函數中調用對象的方法?

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

我創建狗對象Dog('Bowwow')的新實例,但方法sayName()是不確定的。爲什麼?

或者,也許我應該這樣做(但我看不出差別)...

var Dog = function(name) { 

    this.name = name; 

    this.sayName(); 

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

謝謝。

+0

你的第一個代碼示例很好用。你遇到什麼問題?你可以看到它在這裏工作:http://jsbin.com/uxevi3 – 2010-04-15 10:22:26

+0

@Philippe Leybaert,請參閱電子商務答案。我忘了使用新的。 – Kirzilla 2010-04-15 10:26:12

回答

5

JavaScript在這方面有點狡猾,只要您使用new的構造函數調用Dog,您的代碼就可以工作。

new Dog("Hello world") 

新的構造使得this的行爲很像你想讓它。否則它是完全不同的。