window.name = "the window object"
function scopeTest( ) {
return this.name;
}
// calling the function in global scope:
scopeTest()
// -> "the window object"
var foo = {
name: "the foo object!",
otherScopeTest: function() { return this.name }
};
foo.otherScopeTest();// -> "the foo object!"
var foo_otherScopeTest = foo.otherScopeTest;
foo_otherScopeTest();
// –> "the window object"
If you wish to convert an object to a function After assigning a value to another variable, the execution context of this function is still this object, so you need to use the bind method. The implementation of
bind is as follows:
// The . bind method from Prototype.js
Function.prototype.bind = function(){
var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();
return function(){
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
Usage example:
var obj = {
name: 'A nice demo',
fx: function() {
alert(this.name);
}
};
window.name = 'I am such a beautiful window!';
function runFx(f) {
f();
}
var fx2 = obj.fx.bind(obj);
runFx(obj.fx) ;
runFx(fx2);
Reference:
http://www.prototypejs.org/api/function/bind
PS:
I just discovered prototypejs The API documentation is explained in such detail, so be sure to take the time to read more.
My simple implementation:
Function.prototype .bind = function(obj) {
var _this = this;
return function() {
return _this.apply(obj,
Array.prototype.slice.call(arguments));
}
}
var name = 'window',
foo = {
name:'foo object',
show:function() {
return this.name;
}
};
console.assert(foo.show()=='foo object',
'expected foo object,actual is ' foo.show());
var foo_show = foo.show;
console.assert(foo_show()=='window',
'expected is window,actual is ' foo_show());
var foo_show_bind = foo.show.bind( foo);
console.assert(foo_show_bind()=='foo object',
'expected is foo object,actual is ' foo_show_bind());