var
name
=
"clever
coder"
;
var
person
= {
name
:
"foocoder"
,
hello
:
function
(sth){
var
sayhello
=
function
(sth)
{
console.log(
this
.name
+
"
says "
+
sth);
};
sayhello(
}
person.hello(
"hello
world"
);
//clever
coder says hello world
在內部函數中,this沒有按預想的綁定到外層函數對象上,而是綁定到了全局對象。這裏普遍被認爲是JavaScript語言的設計錯誤,因爲沒有人想讓內部函數中的this指向全局對象。一般的處理方式是將this作爲變量保存下來,一般約定爲that或者self:
var
name
=
"clever
coder"
;
var
person
= {
name
:
"foocoder"
,
hello
:
function
(sth){
var
that
=
this
;
var
sayhello
=
function
(sth)
{
console.log(that.name
+
"
says "
+
sth);
};
sayhello(sth);
}
}
person.hello(
"hello
world"
);
//foocoder
says hello world