面向对象的Javascript,为什么对象的方法不能在我的init方法中工作?

时间:2011-12-15 22:02:34

标签: javascript oop

此代码改编自mozilla的介绍到面向对象的js页面:Introduction to Object-Oriented JavaScript

当我运行以下javascript代码时,我没有收到“hello”警告,表明sayHello被正确调用。在mozilla文档中,person对象的创建和调用不属于init函数 - 我将其复制到底部示例中。是什么给了什么?

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

1 个答案:

答案 0 :(得分:3)

window.onload = init();

有你的问题。这将运行init方法,然后将返回值(undefined)应用为onload的{​​{1}}属性。所以没有任何事情发生window;一切都在发生。这意味着它会在您修改onload之前发生。

这样做是为了延迟执行:

Person.prototype