I have a simple object (a button in Sencha Touch actually). It’s in an object called ‘something.aButton()’;
This object contains a property called ‘view’ with a value of ‘home’;
Now I want to assign this to a variable, assign some new properties and pass it on.
So I do:
var c = something.aButton();
Now I assign some more stuff:
c.id = 4;
c.class = 'class';
Now the problem is that c.view is undefined unless I do:
c.view = c.view;
Which – coming from a PHP world baffles the heck out of me. I get the basics of prototypes but don’t understand how I can simply assign my object to a variable for ease of use and work from that. I don’t know all the original properties either so reassigning it like this is not possible in my code and I somehow doubt that this is the proper way.
If I dump ‘c’ to my console I see:
Ext.Object.classify.objectClass
class: "class"
id: 4
__proto__: Object
view: 'home'
....
I would avoid using the identifier
class. It’s a reserved word in the 3rd edition of JavaScript, and in "loose" (non-strict) code in the 5th edition.It’s not undefined. What you’re changing there is whather
chas its own copy of theviewproperty. If you just didconsole.log(c.view)you’d see its value in the console, even without doing the assignment above.The way prototypes work in JavaScript is that the object is backed up by the prototype in a live way. So if you take the value of
viewfromc, andcdoesn’t have its own property calledview, its prototype chain is checked. But if you assign a value toviewonc, thencgains a property of its own with that name, and you see it in object dumps and such.So here’s a simplified example:
At the moment, our object graph looks like this:
So there we have
f, which is backed by the prototypeFoo.prototype. When we askffor the propertybar, sincefdoesn’t have a property of its own by that name, the JavaScript engine looks to its prototype to see if it does. If so, that value is used. (And this continues if the prototype has a prototype, etc.)Now suppose we do this:
Because
fnow has its ownbarproperty, the JavaScript engine uses the value of that property. Now our graph looks like this:We can remove
f‘s property:…and so retrieving
barfromfonce again looks to the prototype, becausefdoesn’t have a property calledbar. We’re back to the original object graph:Now the fun bit: Suppose we change the prototype’s property?
Because
fdoesn’t have abarproperty, the engine looks at the prototype. This is what I meant by it being a live system.