4

I've been trying to further my understanding of javascript namespacing and prototype inheritance but i am running into an issue.

An example of what i'm dealing with code wise:

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 i then try and call a method by doing:

namespace.ex2.method1();

i find that namespace.ex2.method1 is not a function.

What am i missing?

0

3 Answers 3

2

i find that namespace.ex2.method1 is not a function.

Correct. In JavaScript, you don't directly assign prototypes to objects (although that's becoming possible as the new 5th edition gets adopted; see below). Instead, you set up prototypes on constructor functions which are then assigned to objects constructed by those functions. So if you had done

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

...you would have found the method. (Although there's no reason you can't call namespace.ex2.prototype.method1(); if you want to.)

This indirect approach is somewhat unusual for a prototypical language. ECMAscript 5th edition does introduce a means of creating an object and setting its prototype directly (Object.create), but that's a fairly new addition to the language.

For more about prototypes, "methods," setting up prototype chains, etc., you might find this article by Crockford and this rather lesser (but perhaps more familiar-sounding, and certainly pragmatic) one by yours truly interesting reading.

Sign up to request clarification or add additional context in comments.

Comments

0

create instance before

var instance = new namespace.ex1;

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

Comments

0

Prototypes apply to instances of objects:

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

To put a function directly inside an object (instead of in its prototype), do this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.