Defining methods via prototype vs using this in the constructor - really a performance difference?

前端 未结 7 1413
陌清茗
陌清茗 2020-11-22 12:06

In JavaScript, we have two ways of making a \"class\" and giving it public functions.

Method 1:

function MyClass() {
    var privateInstanceVariable         


        
7条回答
  •  粉色の甜心
    2020-11-22 12:59

    You may use this approach and it will allow you to use prototype and access instance variables.

    var Person = (function () {
        function Person(age, name) {
            this.age = age;
            this.name = name;
        }
    
        Person.prototype.showDetails = function () {
            alert('Age: ' + this.age + ' Name: ' + this.name);
        };
    
        return Person; // This is not referencing `var Person` but the Person function
    
    }()); // See Note1 below
    

    Note1:

    The parenthesis will call the function (self invoking function) and assign the result to the var Person.


    Usage

    var p1 = new Person(40, 'George');
    var p2 = new Person(55, 'Jerry');
    p1.showDetails();
    p2.showDetails();
    

提交回复
热议问题