我正在尝试通过此链接了解封装
function Test() {
var prop1 = "one";
this.prop2 = "two";
function meth1() {
console.log("Inside meth1" + prop1);
}
this.meth2 = function() {
console.log(this.prop2 + "................, " + meth1());
};
this.meth4 = function(val) {
prop1 = val;
console.log("inside meth4" + prop1);
}
}
var tc = new Test();
var result1 = tc.meth2();
var result3 = tc.prop1;
根据meth1()
访问的链接this.meth2
应该有效,但令我惊讶的是我没有定义。
您能否说明一下这里发生的事情。我正在为此使用IE 9
LOG: Inside meth1one
LOG: two................, undefined
除了@Michael的答案外,当您尝试将函数作为类时,请记住要返回值。此值将公开可用。在类结构中,var result3 = tc.prop1;
应返回undefined
。访问它的唯一方法应该是功能。以下是代表
function Test() {
// To hold context as object inside functions
var self = this;
self.prop1 = "one";
self.prop2 = "two";
// method to access prop1
function meth1() {
return self.prop1;
}
// method to access prop2
function meth2() {
return self.prop2;
};
// Properties that will be publically available.
// Never add private variables here.
return{
"meth1":meth1,
"meth2":meth2
}
}
var tc = new Test();
var result1 = tc.meth1(); // Should be "one"
var result2 = tc.prop1; // Should be "undefined". Private property
var result3 = tc.meth2(); // Should be "two"
console.log(result1,result2,result3)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句