當我嘗試理解Javascript中的代碼時,遇到了一個奇怪的問題:Good Parts。我嘗試使用的console.log()打印的東西,但我只是得到類型錯誤,我的代碼是在這裏:console.log不是nodejs中的函數6.9.1
Function.prototype.method=function(name,func){
this.prototype[name]=func;
return this;
}
Function.method('bind',function(that){
var method=this;
var slice =Array.prototype.slice;
var args=slice.apply(arguments,[1]);
console.log(that);//error: console.log is not a function
return function(){
return method.apply(that,args.concat(slice.apply(arguments,[0])));
};
});
var x=function(){
return this.value;
}.bind({value:666});
console.log(x());
和錯誤消息的打擊:
/home/wz/code/js/c.js:14
console.log(that);//error: console.log is not a function
^
TypeError: console.log is not a function
at Function.<anonymous> (/home/wz/code/js/c.js:14:13)
at new Console (console.js:34:23)
at console.js:100:18
at NativeModule.compile (bootstrap_node.js:497:7)
at Function.NativeModule.require (bootstrap_node.js:438:18)
at get (bootstrap_node.js:254:34)
at Function.<anonymous> (/home/wz/code/js/c.js:14:5)
at Object.<anonymous> (/home/wz/code/js/c.js:23:3)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
Shell 已返回1
當我在stackoverflow中運行代碼段時,它非常有意思,它的工作原理與我的預期一樣...所以,似乎我的本地環境中存在一些錯誤?
我嘗試使用FS保存的console.log到文件,看看它是什麼其實在我的代碼,我改變了代碼:
fs=require('fs');
Function.prototype.method=function(name,func){
this.prototype[name]=func;
return this;
}
Function.method('bind',function(that){
var method=this;
var slice =Array.prototype.slice;
var args=slice.apply(arguments,[1]);
fs.writeFile('a.txt',String(console.log));
//console.log(that);//error: console.log is not a function
return function(){
return method.apply(that,args.concat(slice.apply(arguments,[0])));
};
});
var x=function(){
return this.value;
}.bind({value:666});
console.log(x());
,並在A.TXT:
function(){
return method.apply(that,args.concat(slice.apply(arguments,[0])));
}
非常精彩,成爲的console.log返回的對象......我完全糊塗了。 我已經試過節點6.9.1和4.6.1,我得到了相同的結果。我用NVM來管理我的節點版本
只需要說明一點:不需要在node.js中像這樣填充「綁定」 - 它本身支持它。 –
'console'本身的價值是什麼? – damd
@damd我改變console.log到控制檯,我得到'[object Object]'在a.txt – wangzhe