Creating functions for an object in javascript

As far as I can tell, there are two main ways to create functions for an object in javascript. It:

Method A, do this in the constructor:

function MyObject() {
    this.myFunc1 = function() {
        ...
    }
    this.myFunc2 = function() {
        ...
    }
    ...
}

Method B, add it to the prototype:

function MyObject() {
    ...
}

MyObject.prototype.myFunc1 = function() {
    ...
}

MyObject.prototype.myFunc2 = function() {
    ....
}

Obviously if you did this:

MyObject.myFunc3 = function() {
    ....
}

it myFunc3will be associated with MyObject on its own, and not with any new objects created with the keyword new. For clarity, we will call it method C, although it does not work to create new objects with a keyword new.

So, I would like to know what are the differences between them. As far as I can tell, they have the same effect logically, even if what happens on the machine is different.

, , , , A, , B ( MyObject), , . , . , A B.

+5
3

, , , " ".

function MyObject(a,b) {
    var n = a + b; //private variable
    this.myFunc1 = function() {
        console.log(n);
    }
};

function MyObject(a,b) {
    this.n = a + b; //public variable
}

MyObject.prototype.myFunc1 = function() {
    console.log(this.n);
}

, , . , , β„– 2, (, make_my_object(a,b)) , β„– 1.

+4

, , ( ) . , , , .

+2

MyObject A . , ( ).

:

MyObject.MyFunc1(); // will not work
var obj = new MyObject();
obj.MyFunc1(); // will work

, . .

:

    function MyObject() {
        var privateVar = "foo";

        this.publicProperty = "bar";

        // public function
        this.publicFunc = function() {
            ...
        }

        // private function
        function privateFunc () {
            ...
        }
    }

B A, - . . , , . . ( )

C . , , :

MyObject.MyFunc1();

, , , .

0

All Articles