是否有一种简洁的方法来实现以下设计模式?
function a() {
function x() { /* code */ }
function y() { /* code */ }
/* more code */
x(); y(); // these can be called here
}
a();
a.x();
a.y();
我最近熟悉了原型(prototype),并且可能会使用这样的东西:
a = function() { }
a.prototype.x = function() { }
a.prototype.y = function() { }
但也许还有更简洁的方法?因为在我的代码中 a
也属于其他东西的原型(prototype),即
function plugin() { ... }
plugin.prototype.a = function () {}
plugin.prototype.a.prototype.x = function () {}
plugin.prototype.a.prototype.y = function () {}
最佳答案
你可以这样写:
function a() {
this.x = function () { /* code */ }
this.y = function () { /* code */ }
/* more code */
this.x(); this.y(); // these can be called here
}
var test = new a();
test.x();
test.y();
关于javascript - JS中有这样的模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10547087/