Prototype Constructor Call
Instead of using the call method, would it be applicable to utilize the following, e.g:
var A = function(height,weight) {
this.height = height;
this.weight = weight;
};
var a = new A("6ft","500lbs");
A.prototype.foo = {
setup: function() {
this.height.set();
this.weight();
},
height: {
set: function() {
var constr = a;
var self = this;
console.log(constr);
开发者_运维知识库 console.log(self);
}
},
weight: function() {
var constr = a;
var self = this;
(function() {
console.log(constr);
})();
}
};
a.foo.setup();
Any suggestions are welcome.
Cheers
You could do this, but what a mess. height
and weight
have two different meanings; all instances of A
will refer back to that initial a
. What is it you're trying to accomplish?
Edit:
The problem with using prototypes is that, when one is created, there is no functional context specific to an instance (for the obvious reason that the prototype is only created once, typically before any instance of the class. Without a context, there's no place to stash variables private to the instance. What I prefer is to create methods at construction:
var A = function(height, weight) {
this.height = function() { return height; };
this.weight = function() { return weight; };
};
Use a function to create the prototype itself creates a common (private, static) context for all instances. You can even mix the concepts:
var A = function(height, weight) {
this.__init__(height, weight);
};
A.prototype.__init__ = (function() {
// any variables declared here are private and static
var number_of_instances = 0;
return function(height, weight) {
// any variables declared here are private and NOT static
// as always, anything added to this are public and not static
this.getNumberOfInstances = function() {
return number_of_instances;
};
this.height = function() { return height; };
this.weight = function() { return weight; };
number_of_instances++;
};
})();
I'm not thrilled about over-writing the entire prototype, that means you couldn't change A to inherit from another class.
精彩评论