简体   繁体   English

使用原型[OOP]的最佳方法

[英]Best way to use Prototype [OOP]

Can you please recommend which of the following is the best or their pros and cons? 您能推荐以下哪项是最好的还是它们的优缺点? I am not sure, but maybe, it depends on the type of use ? 我不确定,但也许取决于使用类型? Is one heavier than the other in terms of performance (keeping the class in memory etc.) ? 在性能方面(将类保留在内存中等),一个是否比另一个重?

Thanks in advance! 提前致谢!

Method 1 方法1

var MyClass = function(something) {
    this.something = something;
}
MyClass.prototype = {
    myMethod: function(arg) {
        this.arg = arg;
        return this.arg;
    },
    mySecondMethod: function() {
            return "helloWorld";
    }
}

Method 2 方法2

var MyClass = (function () {

    function MyClass(something) {
        this.something = something;
    }
    MyClass.prototype.myMethod = function (arg) {
        this.arg = arg;
        return this.arg;
    };
    MyClass.prototype.mySecondMethod = function (arg) {
            return "helloWorld";
    }

    return MyClass;
})();

There are two main differences: 有两个主要区别:

  1. In the first method, you are replacing the default prototype with an entirely new object. 在第一种方法中,您将用一个全新的对象替换默认原型。 That's okay, but instances of MyClass will then inherit the wrong constructor property. 没关系,但是MyClass实例将继承错误的constructor属性。 You can fix that with: 您可以使用以下方法解决此问题:

     MyClass.prototype = { constructor: MyClass myMethod: // etc... 

    Or simply extend the default prototype: 或者只是扩展默认原型:

     var MyClass = function(something) { this.something = something; } MyClass.prototype.myMethod = function(arg) { this.arg = arg; return this.arg; } 
  2. In the second method, you wrapped the whole thing in an immediately-invoked function. 在第二种方法中,您将整个内容包装在立即调用的函数中。 This is useful if you want to have "private" (actually, private-like) variables, as variables declared inside will be visible by functions declared inside, but won't leak to the outer scope: 如果您想拥有“私有”(实际上是类似私有的)变量,这将很有用,因为内部声明的变量将由内部声明的函数可见,但不会泄漏到外部范围:

     var MyClass = (function () { var privateVar = "something"; // this will be visible by the functions // below but not outside function MyClass(something) { this.something = something; } MyClass.prototype.myMethod = function (arg) { this.arg = arg; return this.arg; }; // You were missing this return MyClass; })(); 

These are the differences. 这些是差异。 Both ultimately do the same thing: create a constructor, with some properties/methods attached to the prototype. 两者最终都做同样的事情:创建一个构造函数,并将一些属性/方法附加到原型上。 There's no difference in terms of "optimization". 在“优化”方面没有区别。

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

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