问题描述
当我阅读一些 Angularjs 的 UI 插件示例时,我偶然发现了一些代码,这些代码向我展示了我对 Javascript 的了解是相当有进步的:
As i read through some examples of Angularjs' UI add-on, i've stumbled over some code that showed me that my knowdledge of Javascript is quite improvable:
以下是 Angular 提供者内部的一个类:
The following is a class inside of an Angular provider:
function Dialog(opts) {
var self = this, options = this.options = angular.extend({}, defaults, globalOptions, opts);
this._open = false;
this.backdropEl = createElement(options.backdropClass);
if(options.backdropFade){
// ...
}
this.handleLocationChange = function() {
self.close();
};
// more functions
}
非常简单.但是在该类之外,还有原型函数,例如上面调用的 close()
Pretty straightforward. But outside of that class, there are prototype functions, e.g the above invoked close()
Dialog.prototype.open = function(templateUrl, controller){
var self = this, options = this.options;
// .. some code
};
现在我不明白为什么该函数被声明为原型,而是在类本身内部handleLocationChange
.
Now i do not understand why that function is declared as a prototype, but handleLocationChange
inside the class itself.
我如何决定选择哪种方法?
How do i decide which method to choose?
可以在这里找到完整的要点
推荐答案
考虑这两种情况:
Dialog.prototype.open = function...
Dialog.open = function....
第一种情况 - 每个通过调用 new Dialog()
创建的对象都会有这个 open
函数
First case - every object created by calling new Dialog()
will have this open
function
第二种情况与对话框对象无关,将其视为静态函数.
Second case has nothing to do with dialog objects, consider it as static function.
编辑
在这里找到了一个很好的答案:javascript-class-method-vs-class-原型方法
found a great answer here : javascript-class-method-vs-class-prototype-method
这篇关于更好地理解 Javascript OOP 架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!