// method() 中的 this 指向 foo
//物件.函式()
foo.method();
// method() 中的 this 指向 foo
//物件.函式()
var foo = {
myName ="petter",
sayMyName = function(){
console.log(this.myName);
}
}
foo.sayMyName(); //petter
//this 指向 global
var x = 10;
function foo () {
console.log(this.x);
}
foo(); //10
function People(param) {
this.name = param;
}
var people = new People('petter');
console.log(people.name);
// 'petter'
function foo(that) {
console.log(that.name);
}
var bar = {
name: "I'm bar",
fn:function() {
foo(this);
}
};
bar.fn(); // I'm bar
改變執行對象(function)的 this
fn.call( context, arg1, arg2,... );
fn.apply( context, [ arg1, arg2,... ]);
var foo = {
myName:"petter"
};
function sayMyName(){
console.log(this.myName);
}
sayMyName.call(foo)
改變執行對象(function)的 this
function doCallback(cb,context) {
cb.call(context);
}
var foo = {myName:"petter"};
var sayMyName = function(){console.log(this.myName};
doCallback(sayMyName,foo);
sayMyName.call(foo );
改變執行對象(function)的 this
改變要現在要執行的 function 的 this
function doCallback(cb,context) {
cb.apply(context);
}
var foo = {myName:"petter"};
var sayMyName = function(){console.log(this.myName};
doCallback(sayMyName,foo);
sayMyName.call(foo );
改變要現在要執行的 function 的 this
fn.call( context, arg1, arg2,... );
fn.apply( context, [ arg1, arg2,... ]);
改變要現在要執行的 function 的 this
function sayMyName(arg1,arg2) {
console.log(this.myName, arg1, arg2);
}
var foo = {myName:"petter"};
sayMyName.call(foo,'123','456');
sayMyName.apply(foo,['123','456']);
//petter, 123, 456
回傳一個新的functin並綁定context
fn.bind( context,arg1, arg2 );
回傳一個新的functin並綁定context
function callCb(cb) {
cb();
}
var obj = {
myName:"I'm obj.",
callOther: function(){
var callback = function(){
console.log(this.myName);
}.bind(this);
callCb(callback);
}
}