Function.prototype.call = function(point,...arg){
console.log('ok');
const key = Symbol('key')
point[key] = this
const data = point[key](...arg)
delete point[key]
return data
}
function fn(a,b){
this.sum = a+b
return a + b
}
const obj = {}
const data = fn.call(obj,3,4)
console.log(data);
console.log(obj);
node:internal/bootstrap/switches/is_main_thread:149
if (stdout) return stdout;
^
RangeError: Maximum call stack size exceeded
at process.getStdout [as stdout] (node:internal/bootstrap/switches/is_main_thread:149:3)
at console.get (node:internal/console/constructor:214:42)
at console.value (node:internal/console/constructor:340:50)
at console.log (node:internal/console/constructor:379:61)
at Function.call (C:\Users\xyk\Desktop\my study\nodejs\node.js中级\23重写call函数.js:2:13)
at new WriteStream (node:tty:96:14)
at createWritableStdioStream (node:internal/bootstrap/switches/is_main_thread:53:16)
at process.getStdout [as stdout] (node:internal/bootstrap/switches/is_main_thread:150:12)
at console.get (node:internal/console/constructor:214:42)
at console.value (node:internal/console/constructor:340:50)
Node.js v20.12.1
但是如果将“prototype.call”改为“prototype.Mycall”,就不会出现这个问题了
Function.prototype.Mycall = function(point,...arg){
console.log('ok');
const key = Symbol('key')
point[key] = this
const data = point[key](...arg)
delete point[key]
return data
}
function fn(a,b){
this.sum = a+b
return a + b
}
const obj = {}
const data = fn.Mycall(obj,3,4)
console.log(data);
console.log(obj);
ok
7
{ sum: 7 }
这个问题真让我困惑
如果我删除“console.log()”,问题就会消失。但我想说,对于“prototype.Mycall”的情况,即使有“console.log()”,也不会报错
nodejs
console.log
实现使用.call()
。您的 Function.prototype.call
实现使用 console.log()
。这意味着相互递归,并且由于没有基本情况而导致堆栈溢出。
所以:不要搞乱内置函数!