javascript object problem
i am a little confused. i want to create a javascript object like:
f开发者_如何转开发unction myObject(){
this.keyOne=1;
this.keyTwo=2;
this.keyThree=3;
function add(){
return this.keyOne+this.keyTwo+this.keyThree;
}
return{
add: add
}
}
so creating this object with
var newObject = new myObject();
is working fine and all attributes are correct. but with
var result = newObject.add;
all keys are suddenly undefined! i have no idea why? :/
You're not defining add()
in a way that's exposed, you could do this for example:
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();
You can test it here.
Also note that you need to call add()
with parenthesis, since it's a function, or you'll get the function itself back, not the result.
There currently is no meaning for the keyword public
in standard JavaScript.
Based on your original code snippet, I suspect you meant:
function myObject(){
this.keyOne=1;
this.keyTwo=2;
this.keyThree=3;
function add(){
return this.keyOne+this.keyTwo+this.keyThree;
}
return {
add: add
};
}
The function would then return an object that only has one property: the add
function. That object is created by the object literal after the return
keyword.
But then there is no point using this
. You could have written:
function myObject() {
var keyOne=1;
var keyTwo=2;
var keyThree=3;
function add() {
return keyOne + keyTwo + keyThree;
}
return {
add: add
};
}
Or even more succinctly:
function myObject() {
var keyOne=1;
var keyTwo=2;
var keyThree=3;
return {
add: function() {
return keyOne + keyTwo + keyThree;
}
};
}
This has the added advantage that you don't need to call it prefixed with new
. It's just an ordinary function that creates and returns an object which contains another function:
var o = myObject();
alert(o.add());
You could allow the caller to specify the numbers to be added, like this:
function myObject(keyOne, keyTwo, keyThree) {
return {
add: function() {
return keyOne + keyTwo + keyThree;
}
};
}
var o = myObject(5, 4, 7);
alert(o.add());
精彩评论