Context:(JS上下文)
var obj = {
yes:function(){
this.val=true;
},
no:function(){
this.val=false;
}
};
alert(obj.va);
obj.yes();
alert(obj.val);
上述代码中第一处打印是undefined,第二处打印的是true。说明此时val的上下文变了。
下面更改代码:
var obj = {
yes:function(){
this.val=true;
},
no:function(){
this.val=false;
}
};
obj.yes();
window.no = obj.no;
window.no();
alert(obj.val);
这段代码打印结果还是true,虽然调用了window.no()但是此时val的context已经上升到window,不会影响到obj。
使用Call和Apply可以控制context。
看代码:
var obj = {
yes:function(){
this.val=true;
},
no:function(){
this.val=false;
}
};
function Car(){
//
}
var c = new Car();
obj.yes.call(c);
alert(c.val);
此时打印结果是true,Car对象奇迹般的拥有了val属性。且此时val的作用context只是car对象,即c;如果试着打印alert(obj.val)。得到的结果会是undefined。这样就控制了context的变化。Apply的用法和Call类似。