-
Notifications
You must be signed in to change notification settings - Fork 12
例举 this 的注意点
anyexinglu edited this page May 27, 2019
·
5 revisions
function returnThis(){return this};
var boss1 = {name: 'boss1'};
var boss1returnThis = returnThis.bind(boss1);
var boss2 = {name: 'boss2'};
console.log(boss1returnThis.bind(boss2)())
console.log(boss1returnThis.apply(boss2));
console.log(boss1returnThis.call(boss2));
output:
{name: "boss1"}
{name: "boss1"}
{name: "boss1"}
const returnThis = () => {return this};
var boss1 = {name: 'boss1'};
var boss1returnThis = returnThis.bind(boss1);
var boss2 = {name: 'boss2'};
boss1returnThis.bind(boss2)()
output:
Window
Window
Window
因为箭头函数本质上做了层
bind
。
var value = 1;
var foo = {
value: 2,
bar: function () {
return this.value;
}
}
//示例1
console.log(foo.bar());
//示例2
console.log((foo.bar)());
//示例3
console.log((foo.bar = foo.bar)());
//示例4
console.log((false || foo.bar)());
//示例5
console.log((foo.bar, foo.bar)());
output:
2
2
1
1
1