function myObject(){
this.keyOne=1;
this.keyTwo=2;
this.keyThree=3;
function add(){
return this.keyOne+this.keyTwo+this.keyThree;
}
return{
add: add
}
}
使用
创建此对象var newObject = new myObject();
工作正常,所有属性都正确。但是
var result = newObject.add;
所有键都突然未定义!我不知道为什么? :/
答案 0 :(得分:3)
你没有以暴露的方式定义add()
,你可以这样做:
function myObject(){
this.keyOne=1;
this.keyTwo=2;
this.keyThree=3;
this.add = function(){
return this.keyOne+this.keyTwo+this.keyThree;
}
}
var newObject = new myObject();
var result = newObject.add();
另请注意,您需要使用括号调用add()
,因为它是一个函数,或者您将获得函数本身,而不是结果。
答案 1 :(得分:3)
标准JavaScript中的关键字public
目前没有任何意义。
根据您的原始代码段,我怀疑您的意思是:
function myObject(){
this.keyOne=1;
this.keyTwo=2;
this.keyThree=3;
function add(){
return this.keyOne+this.keyTwo+this.keyThree;
}
return {
add: add
};
}
该函数将返回一个只有一个属性的对象:add
函数。该对象由return
关键字后的对象文字创建。
但是使用this
毫无意义。你可以写:
function myObject() {
var keyOne=1;
var keyTwo=2;
var keyThree=3;
function add() {
return keyOne + keyTwo + keyThree;
}
return {
add: add
};
}
或者更简洁:
function myObject() {
var keyOne=1;
var keyTwo=2;
var keyThree=3;
return {
add: function() {
return keyOne + keyTwo + keyThree;
}
};
}
这样做的另一个好处是,您无需以new
为前缀调用它。它只是一个普通的函数,它创建并返回一个包含另一个函数的对象:
var o = myObject();
alert(o.add());
您可以允许来电者指定要添加的号码,如下所示:
function myObject(keyOne, keyTwo, keyThree) {
return {
add: function() {
return keyOne + keyTwo + keyThree;
}
};
}
var o = myObject(5, 4, 7);
alert(o.add());