0
這個代碼是從Mozilla的介紹適用於面向對象的JS頁:Introduction to Object-Oriented JavaScript面向對象的Javascript,爲什麼對象的方法不能在我的init方法中工作?
當我運行下面的JavaScript代碼,我不明白的「你好」的警報,表明sayHello的正確調用。在Mozilla文檔中,人物對象的創建和調用不屬於初始化函數 - 我將其複製到底層示例中。是什麼賦予了?
window.onload = init();
function init()
{
var person1 = new Person('Male');
var person2 = new Person('Female');
// call the Person sayHello method.
person1.sayHello(); // hello
}
function Person(gender) {
this.gender = gender;
alert('Person instantiated');
}
Person.prototype.sayHello = function()
{
alert ('hello');
};
工作示例:
function Person(gender) {
this.gender = gender;
alert('Person instantiated');
}
Person.prototype.sayHello = function()
{
alert ('hello');
};
var person1 = new Person('Male');
var person2 = new Person('Female');
// call the Person sayHello method.
person1.sayHello(); // hello
你也需要做這行定義`init`功能,而不是之前後。 – 2011-12-15 22:06:04