Andrew said:
If I have some javascript that look like this:
function Car() {
this.color = "red";
this.Describe = Car_Describe;
}
function Car_Describe() {
alert("My car is a " + this.color + " car");
}
Objects created using functions as constructors are in a position to
take advantage of javascript's prototype based inheritance and acquire
their methods through that mechanism:-
function Car() {
this.color = "red";
}
Car.prototype.Describe = function() {
alert("My car is a " + this.color + " car");
}
Apart form making it unnecessary to assign the method to properties of
the object in the constructor (as each constructed object inherits the
method from its prototype instead), simplifying the code and speeding up
object construction, this approach also removes named functions that are
going to be used exclusively as object methods from the global
namespace. Doing so reduces the risk of naming collisions and unexpected
interactions.
var myCar = new Car();
myCar.Describe();
How can I pull the string "myCar" from *this* in the
function Car_Describe?
There is no relationship between an object instance and the name of an
identifier to which a reference to it may have been assigned. It should
be obvious that no such relationship can exist because if you do:-
var objectRef = myCar;
- how could - this - in the object know which of "objectRef" or "myCar"
you were interested in?
In practice object instances might need to be able to arrange some
indirect reference to themselves; calling methods of their own instance
form event handlers and the like. Taht can be arranged but different
approaches suit different contexts so more information would be need
before anything could be suggested.
Richard.