Chr*_*ith 2 javascript oop function object
快问.为什么以下this.testFunction is not a function出错?
Test = {
data: true,
testFunction: function() {
this.data = true;
},
initialize: function() {
this.data = false;
this.testFunction();
console.log(this.data);
}
};
$(document).ready(Test.initialize);
Run Code Online (Sandbox Code Playgroud)
你没有打电话Test.initialize,你正在传递它的价值.这将它与它的上下文分开,所以当它被调用时,this不是Test.
通常的方法是使用匿名函数表达式:
$(document).ready(function () { Test.initialize() });
Run Code Online (Sandbox Code Playgroud)
您还可以使用(使用更有限的浏览器支持)bind:
$(document).ready(Test.initialize.bind(Test));
Run Code Online (Sandbox Code Playgroud)