function myFunction(messager) {
this.message = messager;
}
new myFunction("Hello");
document.write(myFunction.message);
4 Answers
You were trying to reference a member of the function object itself, which is totally incorrect.
When using this in conjunction with the new keyword, this will refer to the object instance which is implicitly returned from the constructor function.
This code should work:
function myFunction(messager) {
this.message = messager;
}
var obj = new myFunction("Hello");
document.write(obj.message);
You can also use the prototype member to augment member functions and variables onto the created objects:
myFunction.prototype.doSomething = function() {
alert('Hello ' + this.message);
}
obj.doSomething(); //alerts "Hello Hello"
myFunction.messageworks if you writemyFunction.message = 'Hello'instead ofnew ..... But there is really no point in doing that.