题目描述
将函数 fn
的执行上下文改为 obj
对象
题目分析
:
函数的执行上下文就是函数中 this 所指向的对象
,那么题目的要求就是 -> 把函数fn
的this指向 obj
对象
- 函数中的 this 指向和函数的定义位置、执行位置无关
- 函数中 this 的指向只取决于函数的调用方式
示例
输入
function () {return this.greeting + ', ' + this.name + '!!!';}, {greeting: 'Hello', name: 'Rebecca'}
输出
Hello, Rebecca!!!
1. 改变函数this
指向的方法
call()
apply()
bind()
详细用法可参照菜鸟教程JavaScript 中 call()、apply()、bind() 的用法
2. 本题解决方法
function speak(fn, obj) {
// return fn.apply(obj);
// return fn.bind(obj);
// return fn.call(obj);
}