为什么我不能引用“'这个'但是当我使用var时我可以吗?

时间:2015-12-13 20:08:18

标签: javascript node.js prototype

抱歉,我甚至不确定如何用这个问题或我甚至应该搜索的内容(Javascript新手的位),最好的解释方法可能是向您展示代码。我试图使用GrovePI节点库(https://github.com/DexterInd/GrovePi/tree/master/Software/NodeJS),但我想抽象一下' board'进入一个带有原型的类,这样我就可以从很多地方引用该板。

以下代码可以解决问题。 '板'已定义,并且在调用board.init()时,我们会成功打印版本。

var GrovePiBoard = function() {

    this.commands = GrovePi.commands;
    var board = new GrovePi.board({
        debug: true,
        onError: function(err){
            console.log('GrovePiBoard.js: Something went wrong');
            console.log(err)
        },
        onInit: function(res) {
            if(res){
                console.log('GrovePiBoard.js: GrovePi Version :: ' + board.version());
            } else {
                console.log('GrovePiBoard.js: res is false');
            }
       }
    });
    // This works
    board.init();
};

GrovePiBoard.prototype.init = function() {
    console.log('Initialising board');
    // I want to do board.init() here.
};

但是,我真的希望能够访问init原型函数上的board对象。像这样......

var GrovePiBoard = function() {
    this.commands = GrovePi.commands;
    this.board = new GrovePi.board({
        debug: true,
        onError: function(err){
            console.log('GrovePiBoard.js: Something went wrong');
            console.log(err)
        },
        onInit: function(res) {
            if(res){
                console.log('GrovePiBoard.js: GrovePi Version :: ' + this.board.version());
            } else {
                console.log('GrovePiBoard.js: res is false');
            }
       }
 });
// This doesn't work here
this.board.init();
};

GrovePiBoard.prototype.init = function() {
    console.log('Initialising board');
    // This doesn't work either
    this.board.init();
};

运行上面的代码时,只要调用ReferenceError: board is not defined,我就会this.board.init();

为什么我不能把电路板放在这个'然后从原型中引用它?

2 个答案:

答案 0 :(得分:1)

虽然这是可行的,但您可能需要查看初始设计。如果您使用prototype.init,那么您正在寻找构造函数。

init与你的功能一起运行(当它被调用时)

请看这个例子,如何调用和使用函数和init。

function GrovePiBoard() {
  var results = this.init.apply(this, arguments); // call the init including the arguments
  console.log('The actual function, init returned: ' + results);
}

GrovePiBoard.prototype.init = function() {
  console.log('The init function');
  return 'Im returned from the init';
};

var GrovePiBoard = new GrovePiBoard();

Jsfiddle:https://jsbin.com/worisikobo/1/edit?js,console

答案 1 :(得分:0)

而不是:

this.board.init();

应该是这样的: Board = new GrovePiBoard(); Board.init();