Skip to content

例举 this 的注意点

anyexinglu edited this page May 27, 2019 · 5 revisions

1、bind 之后再进行 bind/call/apply, 无效!

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"}

image

2、对箭头函数进行 bind/call/apply, 无效!

What is this? The Inner Workings of JavaScript Objects

const returnThis = () => {return this};
var boss1 = {name: 'boss1'}; 
var boss1returnThis = returnThis.bind(boss1);
var boss2 = {name: 'boss2'}; 
boss1returnThis.bind(boss2)()

output:

Window
Window
Window

image

因为箭头函数本质上做了层 bind

3、GetValue(lref) 使得 this 变为全局

JavaScript深入之从ECMAScript规范解读this #7

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

4、小心覆盖全局变量

JavaScript深入之从ECMAScript规范解读this #7

image