When should you use "prototype" while expanding an object in javascript?

I am confused about the concept of "prototype" in javascript.

When I define an object, both working ones look like this:

myObject = {};
myObject.prototype.method1 = function() { ... };
myObject.prototype.method2 = function() { ... };
myObject.prototype.method3 = function() { ... };

and...

myObject = {};
myObject.method1 = function() { ... };
myObject.method2 = function() { ... };
myObject.method3 = function() { ... };

Can anyone shed some light on this? What is the difference between these two ways of creating an object, and why should I choose one after the other? (I have this feeling in my gut is important ...)

Thank!

+5
source share
2 answers

You should use the property prototypeonly constructor Functions , and not in object instances, for example:

function Test () {}
Test.prototype.method1 = function () {/*...*/};

var obj = new Test();

prototype new, .

, .

- [[Prototype]], new - , .

obj , method1 obj, , Test.prototype , , :

typeof obj.method1; // "function"
obj.hasOwnProperty('method1'); // false
obj.method1 === Test.prototype.method1; // true

prototype , , :

var myObject = {};
myObject.prototype = "foo";
myObject.bar = "bar";

// myObject is simply {"prototype":"foo","bar":"bar"}
+8

. , new "".

+1

All Articles