面向对象的Javascript,为什么对象的方法不能在我的init方法中工作?
Object oriented Javascript, why won't an object's methods work from within my init method?
这段代码改编自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
)作为window
的onload
属性。所以什么都没发生,onload
;一切都立即发生。这意味着它发生在修改Person.prototype
之前。
这样做可以延迟执行:
window.onload = init;
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- 有没有任何方法可以将控制器从文件加载到ui路由器$stateProvider中
- 数组在递归方法中设置为null
- 打破承诺链的好方法是什么
- 在使用Polymer'加载所有json文件后执行方法;s的核心ajax
- 使用“;这个“;JavaScript原型方法中的关键字
- 序列化数据属性中对象的最可靠方法
- 使用Objective-C的JavaScript注入方法
- 有没有一种方法可以添加相同的项目val=“0”;4〃;到JavaScript中数组的每个对象
- 对于EmberJs模型,为什么不建议重写“init”方法
- 未捕获的类型错误:对象函数(e,t){return new b.fn.init(e,t,r)}没有方法'feat
- 面向对象的Javascript,为什么对象的方法不能在我的init方法中工作?
- jQuery noConflict shim -为什么init方法从未被调用
- ExtJS: init是一个模板方法,什么是模板方法
- 在init之前引用方法
- 是否有替代ng-init的方法来一直执行
- 在angularjs中处理来自另一个页面的init方法的回调
- init方法内部的javascript推送未正确更新数组长度
- jQuery UI可拖动错误'不能在init'之前调用方法;,更新到1.10.1版本
- _foo 不是函数,当从 Jasmine 中的 init 方法调用时