节点从全局调用子函数

时间:2017-06-25 00:16:25

标签: javascript node.js

我在互联网上搜索没有结果(可能是因为我不知道正确的搜索条件)。我目前正在为我的覆盆子pi编写一个带有节点的脚本,其中我用package控制一个lcd。但是因为我不能在我的电脑上运行这个插件我想嘲笑它。我试过了

var lcd = function(){
lcd.prototype.on = function(){
    lcdStatus = 1;
    console.log("The screen is on");
}
lcd.prototype.off = function(){
    lcdStatus = 0;
    console.log("The screen is of");
}
this.println = function(content, line){
    contentLcd[line] = content;
    console.log("------------------");
    console.log("|", contentLcd[1], "|");
    console.log("|", contentLcd[2], "|");
    console.log("------------------");       
}

this.clear = function(){
    contentLcd = [];
}
}

然后以与常规库相同的方式调用模拟库。

lcd.on():
lcd.println("Hello world!", 1);

我收到错误

lcd.println is not a function

我一直在努力奋斗3个小时。

2 个答案:

答案 0 :(得分:0)

首先,你没有从函数中返回对象,我在函数末尾添加了返回。然后创建一个对象并调用它工作的on方法。执行以下代码

var lcd = function(){
lcd.prototype.on = function(){
    lcdStatus = 1;
    console.log("The screen is on");
}
lcd.prototype.off = function(){
    lcdStatus = 0;
    console.log("The screen is of");
}
this.println = function(content, line){
    contentLcd[line] = content;
    console.log("------------------");
    console.log("|", contentLcd[1], "|");
    console.log("|", contentLcd[2], "|");
    console.log("------------------");       
}

this.clear = function(){
    contentLcd = [];
}

return this;
}

var lcd1 = new lcd()

lcd1.on()

答案 1 :(得分:0)

或者,这是一种更清洁的方式来做你想要的事情:

var lcd = function() {
    var that = this;
    that.lcdStatus;
    that.contentLcd = [];

    that.on = function(){
        that.lcdStatus = 1;
        console.log("The screen is on");
    }
    that.off = function(){
        that.lcdStatus = 0;
        console.log("The screen is of");
    }
    that.println = function(content, line){
        that.contentLcd[line] = content;
        console.log("------------------");
        console.log("| " + that.contentLcd[line] + " |");
        console.log("------------------");       
    }

    that.clear = function(){
        that.contentLcd = [];
    }
};

var LCD = new lcd();

LCD.on();
LCD.println("Hello world!", 1);

正如您所看到的,我格式化了您的代码并添加了关键字that以保留方法的位置"此"。

我希望这有帮助!