FED72. 改变上下文
描述
将函数 fn 的执行上下文改为 obj,返回 fn 执行后的值示例1
输入:
alterContext(function() {return this.greeting + ', ' + this.name + '!'; }, {name: 'Rebecca', greeting: 'Yo' })
输出:
Yo, Rebecca!
HTML/CSS/JavaScript 解法, 执行用时: 841ms, 内存消耗: 77772KB, 提交时间: 2020-12-24
{"css":"","js":"function alterContext(fn, obj) {\n return fn.apply(obj)\n}","html":"","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 843ms, 内存消耗: 77772KB, 提交时间: 2021-06-15
{"css":"","js":"function alterContext(fn, obj) {\n return fn.bind(obj)(); // bind()返回的是一个函数,需要立即执行\n}","html":"","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 843ms, 内存消耗: 77772KB, 提交时间: 2021-01-17
{"css":"","js":"function alterContext(fn, obj) {\n return fn.apply(obj , [...arguments].slice(2))\n}","html":"","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 844ms, 内存消耗: 77772KB, 提交时间: 2021-06-26
{"css":"","js":"function alterContext(fn, obj) {\n var m = eval(fn)\n return m.apply(obj)\n}","html":"","libs":[]}
HTML/CSS/JavaScript 解法, 执行用时: 845ms, 内存消耗: 77748KB, 提交时间: 2020-12-05
{"css":"","js":"function alterContext(fn, obj) {\n return fn.bind(obj)()\n}","html":"","libs":[]}