箭头函数this指向问题
class B {}
B. prototype. a = 1;
B. prototype. add = () => {
this. a++;
};
const b1 = new B();
console. log( b1. a);
const b2 = new B();
b2. add();
console. log( b2. a);
const obj = {
a: 1,
};
obj. add = () => {
console. log( this. a);
};
obj. add();
var name = "The Window";
var object = {
name: "My Object",
getNameFunc: function () {
console.log(this)
return function () {
console.log(this)
return this.name;
};
}
};
console.log(object.getNameFunc()());
var name2 = "The Window";
var object2 = {
name2: "My Object",
getNameFunc: function () {
var that = this;
return function () {
return that.name2;
};
}
};
console.log(object2.getNameFunc()());
console.log('begin')
setTimeout(() => {
console.log('setTimeout 1')
Promise.resolve().then(() => {
console.log('promise 1')
setTimeout(() => {
console.log('setTimeout2 between promise1&2')
})
}).then(() => {
console.log('promise 2')
})
}, 0)
console.log('end')
inner = 'window';
function say() {
console.log(inner);
console.log(this.inner);
}
var obj1 = (function() {
var inner = '1-1';
return {
inner: '1-2',
say: function() {
console.log(inner);
console.log(this.inner);
}
}
})();
var obj2 = (function() {
var inner = '2-1';
return {
inner: '2-2',
say: function() {
console.log(inner);
console.log(this.inner);
}
}
})();
say();
obj1.say();
obj2.say();
obj1.say = say;
obj1.say();
obj1.say = obj2.say;
obj1.say();