Javascript namespacing/prototype issue

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?


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.


create instance before

var instance = new namespace.ex1;

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


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();
链接地址: http://www.djcxy.com/p/17042.html

上一篇: JavaScript命名空间的首选技术

下一篇: Javascript命名空间/原型问题