【问题标题】:Calling a ptototype function调用原型函数
【发布时间】:2017-03-29 03:47:29
【问题描述】:

我正在使用我在网上另一个项目中找到的一段代码,我正在努力使其适应我的需要。我无法找出这个函数最初是如何被调用的,所以我希望在这里找到一些帮助。

var gatewayIP = '192.168.10.21',
sock = new WebSocket('ws://' + gatewayIP + ':8000');
sock.binaryType = "arraybuffer";

// Constructor, expects a socket/stream to write device commands 
function HTDLync(sock, log) {
    this.sock = sock;
    this.log = log;
}

// Change zone power state ('On', 'Off', '1', or '0')
HTDLync.prototype.setPower = function(zone, power) {

    powerStr = power.toString().toLowerCase();

    var packet = Buffer.from([0x02, 0x00, 0x00, 0x04, 0x58]);
    packet.writeUInt8(this.cleanZone(zone), 2);

    if (powerStr == 'on' || powerStr == '1'){
        packet.writeUInt8(0x57, 4);
    }
    else if (powerStr == 'off' || powerStr == '0'){
        packet.writeUInt8(0x58, 4);
    }
    else {
        this.log.warn('Unknown setPower argument:', powerStr);
        return;
    }

    var dataOut = addChecksum(packet);
    this.log.debug('Sending setPower command:', dataOut.toString('hex'));
    msg.payload = dataOut;
};

我已尝试调用以下命令:

setPower('1', 'On');
this.setPower('1', 'On');
HTDLync.setPower('1', 'On');

以上所有都以函数未定义错误出现在控制台中。

我觉得我要么遗漏了一些其他代码,要么错误地调用了这个函数。

我将如何调用这个 setPower 原型函数?

【问题讨论】:

  • 要“访问”HTDLync.prototype.setPower,您(通常)需要一个作为 new HTDLync() 结果的对象 - 例如var x = new HTDLync(blah, blha); x.setPower(whatever, blah);

标签: javascript methods prototype


【解决方案1】:

要调用(原型)方法,首先需要通过调用构造函数来创建类的实例

var obj = new HTDLync(new WebSocket('ws://192.168.10.21:8000'), console);

只有这样你才能调用那个对象的方法:

obj.setPower('1', 'On');

看看MDN对OOP in JSusage of prototypes的介绍。

【讨论】:

    【解决方案2】:

    试试下面的代码:参数不是强制传递的,但正如你在构造函数中提到的那样,你传递它。

    var obj= new HTDLync(agr1,arg2); 
    obj.setPower('1', 'On');
    

    【讨论】:

      【解决方案3】:

      您必须先new HTDLync 才能使用!

      var htdLync = new HTDLync();
      htdLync.setPower('1', 'On');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多