javascript - console.log 不是 nodejs 6.9.1 中的函数

标签 javascript node.js

当我试图理解 Javascript:The Good Parts 中的代码时遇到了一个奇怪的问题。我尝试使用 console.log() 打印一些东西,但我只是得到 TypeError,我的代码在这里:

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 中运行该代码片段时,它按我预期的方式运行时非常有趣...所以我的 native 环境中似乎存在一些错误?

我尝试使用 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 成为返回对象真是太神奇了……我完全糊涂了。 我已经尝试过 Node 6.9.1 和 4.6.1,我得到了相同的结果。我使用 nvm 来管理我的 Node 版本

最佳答案

您在代码中的某处覆盖了 console。为了避免Monkey patching你可以使用构造:

console.log = console.log ||函数(消息){ 警报(消息);};

通过这种构造,您不会覆盖现有功能,只会添加新方法或属性。

关于javascript - console.log 不是 nodejs 6.9.1 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40607224/

相关文章:

javascript - 成功登录 firebase 后,Google Apps 脚本重定向到 HTML 文件

node.js - CRA : The engine "node" is incompatible with this module. 即使我有最新 Node

node.js - 有没有办法强制 npm 生成 package-lock.json?

node.js - 将 NodeJs 与 Firebase 一起使用 - 安全性

javascript - 如何获取node.js中正在运行的进程数

javascript - 在不使用 html5mode 的情况下使用 AngularJS 解析查询字符串的最佳方法

javascript - .url 文件使用什么标记语言?

javascript - Css 菜单下拉

javascript - NodeJS 找不到模块 'grpc'

javascript - 使图像响应