this keyword problem in JavaScript
<script type="text/javascript" src="https://getfirebug.com/firebug-lite.js"></script>
<script>
(function(){
var myLib = function (selector) {
console.log(this);
if(this === window) {
console.log('first if statement executed');
console.log(this);
开发者_开发百科 return new myLib(selector);
}
if(this.window === window){
console.log('second if statement executed');
console.log(this);
return new myLib(selector);
}
};
//expose myLib to the global window object
window.myLib = myLib;
})();
myLib('.someclass')
</script>
In Firefox, this is what gets logged to the console:
Window first if statement executed Object {}In IE8, this is what gets logged to the console:
Window second if statement executed Window Object {}Why does this not point to the window in IE when myLib is invoked, but instead this.window points to the window?
window
is weird. It's both the window
object and the global scope object.
Since window
is the [[Global Context]] then this works:
var o = 5;
window.o === 5; // true
Since window
is a global variable then window.window === window
The fact that in IE8 window !== this
is because IE8 hates you. IE8 really messed up the way it implemented window
as global context and as a global variable.
To solve your code problem change
window.myLib = myLib;
to
window.myLib = function() {
return new myLib();
};
if you're trying to avoid calling myLib without invoking a constructor function you can do something like this:
function myLib(){
if(!(this instanceof myLib)){
return new myLib();
}
}
精彩评论