面试题答案
一键面试- 执行
sayNameFunction()
时发生的情况:- 在 JavaScript 中,函数在调用时,
this
的指向取决于函数的调用方式。当sayNameFunction
被赋值为dog.sayName
后,直接调用sayNameFunction()
,此时this
指向全局对象(在浏览器环境中是window
,在 Node.js 环境中是global
),而不是dog
对象。因为global
或window
上没有name
属性,所以不会正确输出My name is Buddy
,在严格模式下可能会报错(this
为undefined
),在非严格模式下可能输出My name is undefined
。
- 在 JavaScript 中,函数在调用时,
- 修改代码的方法:
- 使用
bind
方法:class Animal { constructor(name) { this.name = name; } sayName() { console.log(`My name is ${this.name}`); } } const dog = new Animal('Buddy'); const sayNameFunction = dog.sayName.bind(dog); sayNameFunction();
bind
方法会创建一个新的函数,在这个新函数中,this
被绑定到bind
方法传入的第一个参数,即dog
对象。所以调用sayNameFunction()
时,this
指向dog
,能正确输出My name is Buddy
。 - 使用箭头函数:
箭头函数没有自己的class Animal { constructor(name) { this.name = name; } sayName() { console.log(`My name is ${this.name}`); } } const dog = new Animal('Buddy'); const sayNameFunction = () => dog.sayName(); sayNameFunction();
this
,它的this
取决于外层作用域的this
。这里外层作用域中this
指向window
或global
,但箭头函数内部调用dog.sayName()
,dog.sayName
中的this
指向dog
,所以能正确输出My name is Buddy
。
- 使用