我是JavaScript新手。 我不知道哪一个代码块比其他代码块更好(基于性能)。 我最近一直在学习JavaScript opps一个月。
利用范围链
解决嵌套函数问题var myObject = {
myProperty: 'I can see the light',
myMethod : function(){
var that = this; // store a reference to this (i.e. myObject) in myMethod scope
var helperFunction = function() { // child function
// logs 'I can see the light' via scope chain because that = this
console.log(that.myProperty); // logs 'I can see the light'
//console.log(this); // logs window object, if we don't use "that"
}();
}
}
myObject.myMethod(); // invoke myMethod
var myObject = (function(wn){
return {
myProperty: 'I can see the light',
myMethod : function(){
var helperFunction = function() {
console.log(wn.myObject.myProperty); // logs 'I can see the light'
}();
}
}
}(this));
myObject.myMethod(); // invoke myMethod