Javascript
"this"
this指向於調用該函式之物件
// method() 中的 this 指向 foo
//物件.函式()
foo.method();
this指向於調用該函式之物件
// method() 中的 this 指向 foo
//物件.函式()
var foo = {
myName ="petter",
sayMyName = function(){
console.log(this.myName);
}
}
foo.sayMyName(); //petter
this指向全域物件
//this 指向 global
var x = 10;
function foo () {
console.log(this.x);
}
foo(); //10
this 指向 new 的物件
function People(param) {
this.name = param;
}
var people = new People('petter');
console.log(people.name);
// 'petter'
傳遞tihs
function foo(that) {
console.log(that.name);
}
var bar = {
name: "I'm bar",
fn:function() {
foo(this);
}
};
bar.fn(); // I'm bar
bind
call
apply
改變執行對象(function)的 this
fn.call( context, arg1, arg2,... );
fn.apply( context, [ arg1, arg2,... ]);
apply
call
apply
call
var foo = {
myName:"petter"
};
function sayMyName(){
console.log(this.myName);
}
sayMyName.call(foo)
改變執行對象(function)的 this
apply
call
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
apply
call
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
apply
call
fn.call( context, arg1, arg2,... );
fn.apply( context, [ arg1, arg2,... ]);
改變要現在要執行的 function 的 this
apply
call
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
bind
回傳一個新的functin並綁定context
fn.bind( context,arg1, arg2 );
bind
回傳一個新的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);
}
}
The End
Javascript "this"
By mangogan
Javascript "this"
- 523