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

Object oriented Javascript, why won't an object's methods work from within my init method?

本文关键字:方法 init 我的 工作 不能 为什么 对象 面向对象的 Javascript      更新时间:2023-09-26

这段代码改编自mozilla的面向对象js入门页面:Introduction to oriented JavaScript

当我运行以下javascript代码时,我没有得到指示正确调用sayHello的"hello"警告。在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

window.onload = init();

这就是你的问题。这将运行init方法,然后将返回值(undefined)作为windowonload属性。所以什么都没发生,onload;一切都立即发生。这意味着它发生在修改Person.prototype之前。

这样做可以延迟执行:

window.onload = init;