[英]jS OOP nested functions
好的,對於OOP來說,這可能是一個新問題。
我試圖建立一個JS對象庫的東西,想知道我是否可以使用嵌套函數呢?
var object = new function() {
this.action1 = function () {
this.dostuff1 = function () {
return "dostuff1";
};
this.dostuff2 = function () {
return "dostuff2";
};
};
我在訪問第三級功能時遇到問題。 我可以這樣築巢嗎?
this.action2 = function () {
return "action2";
};
alert(object.action1.dostuff2());
盡管Eberlin的答案是完全正確的,但我建議您創建一個嵌套對象,該對象又將暴露函數而不是嵌套函數本身。 否則,這可能成為可維護性的噩夢。
基本上你可以創建
var Child = function(){
//constructor
};
Child.prototype.doStuff2 = function(){
return "dostuff2";
};
var Root = function(obj){
//constructor
this.child = obj;
};
Root.prototype.action1 = function(){
return "doStuff1";
};
//usage
var myRoot = new Root(new Child());
myRoot.action1();
myRoot.child.action2();
這是一個實時示例: http : //jsbin.com/ijotup/edit#javascript,live
參見下面的一些代碼清理:
var o = (new function () { // changed 'object' to 'o'
this.action1 = (function () { // added parentheses, not required.
this.dostuff1 = (function () { // does not return anything.
return "dostuff1"; // and is also not the proper way to organize
}); // ** look at the javascript prototype
return this; // now it does
}); // missing closing bracket
this.dostuff2 = (function () {
return "dostuff2";
});
});
alert(o.action1().dostuff2()); // action1 is a function, not a variable.
希望這可以幫助。 另外,這是有關javascript原型的簡短教程 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.