【发布时间】:2013-09-19 22:57:24
【问题描述】:
我正在学习一个库,看到一个示例,但我不明白它是如何完成的? 在类的函数中,“this”变量包含类的所有方法。 只有外部的公共方法可用。
受保护的方法更有趣。它们仅在继承的类中可用。 它是如何工作的?
请参阅以下文档中的示例:
/**
* A-class
*/
var ClassA = AWeb.class({
public : {
/**
* A-class constructor
*/
constructor : function() {
/* Private variable */
this.variable1 = "A";
this.calls = 0;
},
/**
* Function returns information about the object
*/
getInfo : function() {
this.incCalls();
return "variable1=" + this.variable1 + ", calls=" + this.calls;
}
},
protected : {
/**
* Protected function
*/
changeVariable1 : function( value ) {
this.variable1 = value;
}
},
private : {
/**
* Private function
*/
incCalls : function() {
this.calls++;
}
}
});
/**
* C-class
*/
var ClassC = AWeb.class({
extends : ClassA,
public : {
/**
* B-class constructor
*/
constructor : function() {
this.super();
this.changeVariable1( "C" );
},
/**
* Function returns extended information about the object
*/
getLongInfo : function() {
return this.incCalls !== undefined ? "incCalls visible" : "incCalls undefined";
}
}
});
/**
* Main project function
*/
function main() {
var a = new ClassA(),
c = new ClassC();
alert(
"a instanceof ClassA: " + (a instanceof ClassA) + "\n" +
"a instanceof ClassC: " + (a instanceof ClassC) + "\n" +
"a.getInfo " + (a.getInfo ? "exists" : "undefined") + "\n" +
"a.getLongInfo " + (a.getLongInfo ? "exists" : "undefined") + "\n" +
"a.changeVariable1 " + (a.changeVariable1 ? "exists" : "undefined") + "\n" +
"a.getInfo()=" + a.getInfo() + "\n\n" +
"c instanceof ClassA: " + (c instanceof ClassA) + "\n" +
"c instanceof ClassC: " + (c instanceof ClassC) + "\n" +
"c.getInfo " + (c.getInfo ? "exists" : "undefined") + "\n" +
"c.getLongInfo " + (c.getLongInfo ? "exists" : "undefined") + "\n" +
"c.changeVariable1 " + (c.changeVariable1 ? "exists" : "undefined") + "\n" +
"c.getInfo()=" + c.getInfo() + "\n" +
"c.getLongInfo()=" + c.getLongInfo()
);
}
【问题讨论】:
-
请澄清您的问题。如果您对封装原理 (en.wikibooks.org/wiki/…) 或它在 JS 中的工作原理感兴趣 (javascript.crockford.com/private.html & nemisj.com/protected-javascript)
-
我简直不敢相信它完全有效。要么他们是在骇人听闻地到处乱砍,要么他们只是假装它。看到
AWeb.class的实现,说不定还能多说,但是网上找不到代码。请发布您想要解释的库本身(相关部分,或至少链接代码),而不是其使用示例:-) -
抱歉这个不准确的问题。我知道javascript中的继承原则。我对指定库中继承的实现感兴趣。它有效,我测试了它。图书馆是免费的,但它有一个封闭的代码,无法阅读。它适用于所有浏览器。我把指定的代码封装到了html页面中,请看。
标签: inheritance scope javascript