我试图完全掌握JavaScript inheritance 和 encapsulation 。采用以下示例( and here is a fiddle of it ):
myPage = {
someObj: function() {
var x = 0;
//PRIVATE: increment by 10
var inc10 = function() {
x = x+10;
};
//PUBLIC: increment
this.inc = function() {
x = x+1;
};
//PUBLIC: decrement
this.dec = function() {
x = x-1;
};
//PUBLIC: output the current value of x
this.getValue = function() {
return x;
}
inc10(); //as soon as obj1 is created lets add 10
this.inc(); //as soon as obj1 is created lets add 1 more
}
};
obj1 = new myPage.someObj(); //x starts out at 11
// obj1.inc10(); won't work because it's private, excellent
obj1.dec();
obj1.inc();
alert(obj1.getValue());
我的问题是关于inc()
方法。我需要它可以从对象的内部和外部调用。这是正确的方法吗?
答案 0 :(得分:1)
我需要它可以从对象的内部和外部调用。这是正确的方法吗?
您的脚本似乎已按预期工作,您在构造函数中将方法调用为this.inc()
非常正确 - 不确定为什么需要改进。
然而,您可以将其定义为本地函数,然后将其作为方法导出 - 并使其仍然可用"内部"作为局部变量:
function SomeObj() {
// local declarations:
var x;
function inc10() {
x = x+10;
}
function inc1() {
x = x+1;
}
// exported as property:
this.inc = inc1; // <== the function from above, not a literal
this.dec = function() {
x = x-1;
};
this.getValue = function() {
return x;
};
// initialisation:
x = 0;
inc10();
inc1(); // this.inc() would still work
}
答案 1 :(得分:0)
从内部和外部调用函数而不将其附加到对象。
这应该有用......
myPage = function() {
var x = 0;
//PRIVATE: increment by 10
var inc10 = function() {
x = x+10;
};
//PUBLIC: increment
this.inc = function() {
x = x+1;
};
//PUBLIC: decrement
this.dec = function() {
x = x-1;
};
//PUBLIC: output the current value of x
this.getValue = function() {
return x;
}
inc10(); //as soon as obj1 is created lets add 10
this.inc(); //as soon as obj1 is created lets add 1 more
};
obj1 = new myPage; //x starts out at 11
// obj1.inc10(); won't work because it's private, excellent
obj1.inc();
alert(obj1.getValue());