gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:11:23 25 4
gpt4 key购买 nike

这段代码改编自mozilla的面向对象js页面介绍:Introduction to Object-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;

关于javascript - 面向对象的 Javascript,为什么对象的方法不能在我的 init 方法中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8527233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com