如何区别JavaScript中的this指向
类型一:在函数中直接调用的
function greet(text) {
console.log(text);
}
greet("Hello");
greet.call(window, "Hello");
类型二:函数作为对象的方法被调用的
let person = {
name: "张三",
sayHello: function(text) {
console.log(`${this.name}笑着向你说:${text}`);
}
}
person.sayHello("Hello");
person.sayHello.call(person, "Hello");
一道面试题
var name = 222;
var a = {
name: 111,
say: function() {
console.log(this.name);
}
}
var fun = a.say;
fun();
a.say();
var b = {
name: 333,
say: function(fn){
fn();
}
}
b.say(a.say);
b.say = a.say;
b.say();
var name = 222;
var a = {
name: 111,
say: function() {
console.log(this.name);
}
}
var fun = a.say;
fun();
a.say();
var b = {
name: 333,
say: function(fn){
fn();
}
}
b.say(a.say);
b.say = a.say;
b.say();
箭头函数中的this
- 箭头函数内部没有绑定this机制,即箭头函数没有this,导致箭头函数的this指向外层代码块的this
var x = 11;
var obj = {
x: 22,
say: () => {
console.log(this.x);
}
}
obj.say();
var x = 11;
var obj = {
x: 22,
say: function(){
var x = 33;
var fn = () => {
console.log(this.x)
}
return fn();
}
}
obj.say();