简体   繁体   English

这是对JavaScript原型的不良使用吗?

[英]Is this bad use of javascript prototype?

I have a javascript module for creating Menu objects originally designed like this: 我有一个javascript模块,用于创建最初设计如下的Menu对象:

// original Menu module
function Menu ( ) {
    alert ( "Menu ( )");
}

Menu.prototype.init = function ( ) {
    alert ( "Menu.init ( )");
}

var menu = new Menu;

I now wish to wrap that inside my API like so 我现在希望像这样将其包装在我的API中

// new API containing Menu
( function ( $api, window, undefined ) {        

    $api.Menu = function ( ) {
        alert ( "$api.Menu ( )");
    };

    $api.Menu.prototype.init = function (  ) {
        alert ( "$api.Menu.init ( )");
    };

}( window.$api = window.$api || {}, window ));

var menu = new $api.Menu;

It appears to work but my question is whether this is correct? 看来可行,但我的问题是这是否正确? eg would this end up duplicating each prototype function for each $api.Menu instance? 例如,这最终会为每个$ api.Menu实例复制每个原型函数吗?

I ask because I've always used prototype with the first method and I'm simply unsure what Javascript is doing under the hood for the second example. 我问是因为我一直将原型与第一种方法结合使用,而我不确定第二个示例在做什么。

There isin't any difference between both in terms of efficiency, the only difference is that you are namespacing your constructor in the second example, which is a better practice than polluting the global namespace. 两者在效率方面没有任何区别,唯一的区别是在第二个示例中您要命名构造函数的名称,这比污染全局名称空间更好。

However the following would have been inefficient, since we would create a new init function everytime the constructor is getting called and we would not make use of the prototype chain at all to share functions between instances, resulting in a higher memory usage. 但是,以下操作效率低下,因为每次构造函数被调用时我们都会创建一个新的init函数,并且我们根本不会利用原型链在实例之间共享函数,从而导致更高的内存使用率。

function Menu() {
    this.init = function () {};
}

They will all work, javascript is flexible like that. 他们都会工作,而javascript则很灵活。
I tend to prefer an object/class setup like: 我倾向于喜欢这样的对象/类设置:

function Menu(e){
   this.init(e);
}
Menu.prototype = {
   a:null,
   b:null,
   init:function(config){
      this.a = config.a;
   },
   doSomething:function(){
      this.b = 'World';
   },
   getSomething:function(){
       return this.a + ' ' + this.b;
   }
}

var menu = new Menu({a:'Hello'});
menu.doSomething();
alert(menu.getSomething());

You just have to remember to maintain scope as far as what "this" is. 您只需要记住保持范围就“ this”是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM