Javascript 使用变量作为Foo.prototype的简写
我刚开始在JavaScript中使用模块模式来声明函数对象,但发现在声明所有可能需要的公共函数时重复Foo.prototype关键字很烦人 因此,为了方便起见,我想到了使用一些速记变量,如下所示Javascript 使用变量作为Foo.prototype的简写,javascript,design-patterns,prototype,Javascript,Design Patterns,Prototype,我刚开始在JavaScript中使用模块模式来声明函数对象,但发现在声明所有可能需要的公共函数时重复Foo.prototype关键字很烦人 因此,为了方便起见,我想到了使用一些速记变量,如下所示 (function(){ var Foo = function(){ alert('created Foo'); } // shorthand for further creation of public functions var pro = Foo.pr
(function(){
var Foo = function(){
alert('created Foo');
}
// shorthand for further creation of public functions
var pro = Foo.prototype;
//public function with shorthand
pro.bar = function(){
//some cool stuff here
}
return window.Foo = Foo;
}());
问题是:是否有理由阻止我保存有关功能或意外错误的这几个字符,或者这样做安全吗?
就我所知,原型在修改它时与其他任何对象都一样。保留对它的引用是绝对可以的据我所知,当涉及到修改原型时,原型与其他任何对象一样。保留对它的引用绝对可以编辑: 这样做是可以的,但如果有这样的代码,有时会让人感到困惑:
var pro='123';
(function () {
var Foo=function () {
alert('created Foo');
};
// shorthand for further creation of public functions
var pro=Foo.prototype;
var x=new Foo();
alert(pro);
})();
alert(pro);
或者不经意地这样写:
var pro='123';
(function () {
var Foo=function () {
alert('created Foo');
};
// use pro without var
pro=Foo.prototype;
var x=new Foo();
alert(pro);
})();
alert(pro);
前者可以正常工作,只是在阅读代码时容易混淆,读者需要意识到IIFE中的var pro
在全局范围内是不同的pro
后者可能是一个可怕的错误,pro
被重新分配并丢失其原始值
因此,我在最初的答案中提出了代码,因为您不能在函数内部修改此
我想你可以这样做
var Foo=(function () {
function Foo() {
alert('created Foo');
}
// inside the anonymous function `this` is `Foo.prototype`
(function () {
this.bar=function () {
//some cool stuff here
};
}).call(Foo.prototype);
return Foo;
})();
var x=new Foo();
x.bar();
编辑:
这样做是可以的,但如果有这样的代码,有时会让人感到困惑:
var pro='123';
(function () {
var Foo=function () {
alert('created Foo');
};
// shorthand for further creation of public functions
var pro=Foo.prototype;
var x=new Foo();
alert(pro);
})();
alert(pro);
或者不经意地这样写:
var pro='123';
(function () {
var Foo=function () {
alert('created Foo');
};
// use pro without var
pro=Foo.prototype;
var x=new Foo();
alert(pro);
})();
alert(pro);
前者可以正常工作,只是在阅读代码时容易混淆,读者需要意识到IIFE中的var pro
在全局范围内是不同的pro
后者可能是一个可怕的错误,pro
被重新分配并丢失其原始值
因此,我在最初的答案中提出了代码,因为您不能在函数内部修改此
我想你可以这样做
var Foo=(function () {
function Foo() {
alert('created Foo');
}
// inside the anonymous function `this` is `Foo.prototype`
(function () {
this.bar=function () {
//some cool stuff here
};
}).call(Foo.prototype);
return Foo;
})();
var x=new Foo();
x.bar();
这很好,但是不要忘记
var
您的变量Foo
@Xotic750:那么就没有理由运行该代码,因为Foo
在外部是无法访问的。我相信Foo
旨在实现全局性,但更好的方法是var Foo=。。。;window.Foo=Foo代码>。编辑:也许不是,谁知道:DFelix是对的!不再可见。我想我需要把window.foo作为updated@Felix:是的,谁知道呢,但我猜这就是我的意图。或者可能返回到另一个外部本地服务器。:)这很好,但是不要忘记var
您的变量Foo
@Xotic750:那么就没有理由运行该代码,因为Foo
在外部是无法访问的。我相信Foo
旨在实现全局性,但更好的方法是var Foo=。。。;window.Foo=Foo代码>。编辑:也许不是,谁知道:DFelix是对的!不再可见。我想我需要把window.foo作为updated@Felix:是的,谁知道呢,但我猜这就是我的意图。或者可能返回到另一个外部本地服务器。:)是的,但这并不能回答OP的问题;)谢谢这是另一篇帮助我理解整件事的文章@菲利克斯克林:嗯。。现在好些了吗?是的,但这并不能回答OP的问题;)谢谢这是另一篇帮助我理解整件事的文章@菲利克斯克林:嗯。。现在好些了吗?