[英]javascript : Cannot access member function
NEWBIE question. NEWBIE问题。
I cannot access member function. 我无法访问会员功能。 What am I doing wrong?
我究竟做错了什么?
index.js ->
var abc = require('./def');
var foo = new abc();
foo.zxc();
def.js ->
var bar = function(){
// do something
var zxc = function(){
// do something
}
}
module.exports = def;
When I run in brwoser console it shows : 当我在brwoser控制台中运行时,它显示:
TypeError:foo.zxc is not a function TypeError:foo.zxc不是函数
Because zxc
is just a local variable not accessible from outside of the the bar
function. 因为
zxc
只是一个无法从bar
函数外部访问的局部变量。 You can change it to 你可以把它改成
var bar = function() {
// do something
this.zxc = function(){
// do something
}
}
Now, zxc
is an own property of the constructed object so it will work. 现在,
zxc
是构造对象的自有属性,因此它可以工作。
Try something like the following: 尝试以下内容:
// index.js ->
var abc = require('./def');
var foo = new abc.bar();
foo.zxc();
// def.js ->
var bar = function(){
// do something
this.zxc = function(){
// do something
}
}
module.exports.bar = bar;
The main difference is you are now exporting the bar() {...}
constructor which can then be used off of the abc
required in module? 主要的区别是你现在导出
bar() {...}
构造函数,然后可以使用模块中所需的abc
吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.