- 直接调用的函数this指向window
function greet(text) {
console.log(text);
}
greet("Hello");
greet.call(window, "Hello");
类型二:函数作为对象的方法被调用的
- 谁调用函数,函数的this就指向谁
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();