I am new here so I hope I do not violate any rules…
It is so that I am working on object inheritance in JavaScript… and are figuring out “my” rules for this thing… And now I have come to “some” sort of a problem…
this is what I like to do:
I like to have an method (function) that is more an identifier for the object I am creating, this method is also the objects creator… However I also wish to use that same object to instantiate the “datatype” the object created (I guess code explains more so… here is the piece I am stuck with)
TRecord = function() {
this.Class = 'TRecord';
F = function() {};
F.prototype = arguments[0]; //args is an object (se below)
return(new F());
};
TRecord.create = function(O) { // this method will not be executed as I like
if(O) alert(O.Class); // inside above object when define there with
<new O object created and returned - code missing>
}; // this.create = function(){};
// but if defined here it will, se below...
TMessage = TRecord({
'Class': 'TMessage',
'msgID': Number(0),
'data': Object('Hello')
});
aMSG = TRecord.create(TMessage); // the TMessage instance will be created
// with the above method... and
alert(aMSG.Class); // will output TMessage...
why can’t I implement the TRecord.create function inside TRecord ?
…
I have some trouble posting the whole source.js (the formatting do not work) so this will have to due, I do however have some other constructors/creator functions for “real” function (class) objects and not records (data objects)… that works – these are Implemented a bit different though, with support for deep inheritance…
The
thiskeyword refers to the scope under which a function is called. In your example:TRecord will be called with the
globalorwindowobject as its scope, or in strict mode,undefined. Thethiskeyword only refers to a new object inside of a constructor function because of how thenewkeyword boxes a call with the new scope.For more information, please see https://developer.mozilla.org/en/JavaScript/Reference/Operators/this