Javascript namespacing / prototype issue

I tried to expand my understanding of javascript namespace and prototype inheritance, but I ran into a problem.

An example of what I mean with the code:

var namespace = { ex1: function () { }, ex2: function () { this.exvar1 = 0, this.exvar2 = 0; } } namespace.ex1.prototype = { method1: function () { }, method2: function () { } }; namespace.ex2.prototype = { method1: function () { alert("ex2.method1" + typeof this.method1); }, method2: function () { alert("ex2.method2" + typeof this.method2); } }; 

if then I try to call the method by doing:

 namespace.ex2.method1(); 

I found that namespace.ex2.method1 is not a function.

What am I missing?

+4
source share
3 answers

I found that namespace.ex2.method1 is not a function.

Right. In JavaScript, you do not directly assign prototypes to objects (although this becomes possible as a new fifth release , see below). Instead, you set up prototypes of constructor functions, which are then assigned to the objects built by these functions. So if you did

 var obj = new namespace.ex2(); obj.method1(); 

... you would find a method. (Although there is no reason why you cannot call namespace.ex2.prototype.method1(); if you want.)

This indirect approach is somewhat unusual for a prototypical language. The fifth edition of ECMAscript introduces the means of creating an object and directly defining its prototype ( Object.create ), but this is a fairly new addition to the language.

Read more about prototypes, methods, settings of prototype chains, etc. you can find this article from Crockford and this is a less (but perhaps more familiar, and, of course, pragmatic) really interesting reading.

+2
source

create an instance before

 var instance = new namespace.ex1; 

try here http://jsfiddle.net/quWPC/

0
source

Prototypes apply to instances of objects:

 var foo = function() {}; foo.prototype = { a: function() {} } var instance = new foo; instance.a(); 

To place a function directly inside an object (and not in its prototype), do the following:

 var foo = function() {}; foo.a = function() {}; foo.a(); 
0
source

Source: https://habr.com/ru/post/1334141/


All Articles