0

I'll admit I'm flailing around, cobbling code together from different authors in an attempt to figure out javascript prototypes.

I'm new to the prototype concept, and would like to have some instance variables in my class that can be modified using a method.

Here's what I'm trying, in essence. This was cribbed and modified from the web:

var MyGlobe = function () {
    var self = this;
    self.variable1 = null;
    return self;
}

MyGlobe.prototype = function () {
    var setup = function () {
        this.variable1 = 33;
    };
     return {
        setup:setup
    };
 }();

...the point of all that is so I can call the setup method on an instance of MyGlobe and set variable1 properly:

var aGlobe = new MyGlobe();
aGlobe.setup();

//aGlobe.variable1 is 33 now

This actually seems to work, but I'm not sure why the original author did things this way? For instance, what's the point of the self.variable1 bit at the beginning?

Is it preferable to typing out:

MyGlobe.prototype.variable1;
MyGlobe.prototype.variable2;
//....

I also thought you'd do something like self=this if you thought your class would be used in a callback function for example, but that doesn't appear to be the case here? (Happy to be shown wrong.)

I'm not sure what the best practices are here and would like to know more.

4

1 に答える 1

1

This actually seems to work, but I'm not sure why the original author did things this way? For instance, what's the point of the self.variable1 bit at the beginning?

None (for using self), the "declaration of instance properties" (even if only initialising them to null) can help engines to use more memory-efficient internal structures - though it's not really necessary.

I also thought you'd do something like self=this if you thought your class would be used in a callback function for example, but that doesn't appear to be the case here?

Exactly. This small snippet really should be rewritten to

var MyGlobe = function () {
    this.variable1 = null;
}
MyGlobe.prototype.setup = function() {
    this.variable1 = 33;
};

Is it better to declare the instance variables in the constructor function (self.variable1) as opposed to adding them to the prototype (MyGlobe.prototype.variable1)?

That's simple. On the prototype it's no instance property any more. And please distinguish between variables (like self - which are local-scoped to the function) and properties (like prototype, setup or variable1 - which are "public" on the object).

于 2013-03-25T14:54:01.133 に答える