On Jan 14, 3:04 pm, yawnmoth <terra1...@yahoo.comwrote:
Based on my understanding of the apply function, the following code
snippet should, at the very least, not yield any errors.
Unfortunately, it does, suggesting my understanding is... limited.
Any ideas as to what's wrong?:
<script>
function simpleClass(value) {
this.value = value;
}
(function() {
this.displayValue = function() {
alert("value = " + this.value);
};
this.changeValue = function(value) {
this.value = value;
};
}).apply(simpleClass);
What you are doing here is calling the anonymous function and setting
its this keyword as a reference to the simpleClass function object.
Therefore, the changeValue property is added to the simpleClass
object.
Try:
alert(typeof simpleClass.changeValue); // --function
a = new simpleClass("abcd");
a.changeValue("efgh");
"a" is a function object constructed from the simpleClass function.
It only has the properties that were added in the constructor and
those that are on the prototype chain. The simpleClass object isn't
on a's prototype chain, so neither is the changeValue property that
you added to simpleClass.
alert(typeof a.changeValue); // --undefined
Change the assignment to:
(function() {
...
}).apply(simpleClass.prototype);
and you'll have more luck. Presumably this is just play, I would not
recommend such obfuscated code for assigning to the prototype
property. Just write it:
simpleClass.prototype.changeValue = function(){ ... }
--
Rob