我是C#中经验丰富的编码员,现在我已经处理过nodejs ..而且我无法按照我的预期让它工作:)
我有一个像这样声明的“类”:
var Gpio;
function Lights()
{
[.more variables declared the same way..]
this.o1 = "";
this.o2 = "";
}
//then I have some methods added like this:
Lights.prototype.Init = function()
{
var Gpio = require('pigpio').Gpio,
//init of my variables
o1 = new Gpio(17, {mode: Gpio.OUTPUT}),
o2 = new Gpio(18, {mode: Gpio.OUTPUT});
}
//then I have other methods that try to use o1 and o2
//that where already defined and initialiced
Lights.prototype.On = function(id)
{
if(id == 1)
o1.digitalWrite(true);
else if(id == 2)
o2.digitalWrite(true);
}
但是当我跑步时,我得到了:
o1.digitalWrite(false);
^
ReferenceError: o1 is not defined
如何通过这些方法制作那些o1 o2 o3可访问物?
答案 0 :(得分:1)
与Java,C#和其他语言不同,在JavaScript中, this
关键字在访问实例变量时不可选。
您收到ReferenceError
,因为当前范围内没有名为o1
的变量。
尝试将其更改为:
Lights.prototype.On = function(id)
{
if(id == 1)
this.o1.digitalWrite(true);
else if(id == 2)
this.o2.digitalWrite(true);
}
(当然,您还需要更改Init
方法)
作为最后一点,nodeJS支持ES6,其中包括class declarations - 它们使JS代码更整洁(更像是C#),这可能对你有帮助。
以下是我为您的课程编写代码的方法:
const Gpio = require('pigpio').Gpio;
class Lights {
constructor() {
// there's no need to explicitly declare o1 and o2 here - they'll get
// created whenever they are assigned to. This is just for readability.
this.o1 = null;
this.o2 = null;
// add any more properties here in the constructor - you can't
// declare them in the class body like C#
this.another = 5;
}
init() {
// I'm assuming there's a reason you haven't done this in the constructor
this.o1 = new Gpio(17, {mode: Gpio.OUTPUT}),
this.o2 = new Gpio(18, {mode: Gpio.OUTPUT});
}
on(id) {
// this assumes that init() has been called
switch (id) {
case 1: this.o1.digitalWrite(true); break;
case 2: this.o2.digitalWrite(true); break;
}
}
// methods can be static too
static HELLO() {
// you would call this method with Lights.HELLO()
console.log('hello');
}
}
// if you need to access the Lights class from another nodejs source file, you'll
// need to export it (there's a few ways to do this, so read the docs)
exports.Lights = Lights;
// in main.js - import the Lights class and instantiate it
const Lights = require('./lights.js').Lights;
var light = new Lights();
light.init();
light.on(1);
// also note, there's no visibility restrictions in JS - all
// properties and methods are public.
console.log(light.another);
如果您了解C#,这应该很容易理解。