0
function myFunction(messager) {
    this.message = messager;
}
new myFunction("Hello");
document.write(myFunction.message);
1
  • 1
    myFunction.message works if you write myFunction.message = 'Hello' instead of new ..... But there is really no point in doing that. Commented Dec 29, 2010 at 12:44

4 Answers 4

4

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"
Sign up to request clarification or add additional context in comments.

Comments

3

The new keyword causes this to refer to the instance of the object and not to the constructor function.

function myFunction(messager) {
    this.message = messager;
}
var instance = new myFunction("Hello");
document.write(instance.message);

Comments

3

You need to create a new instance and use that instead:

function myFunction(messager)
{
    this.message = messager;
}

var mf = new myFunction("Hello");
document.write(mf.message);

Comments

0

There're already excellent answers so I'll just provide a simple one. This code creates an instance but doesn't store it anywhere:

new myFunction("Hello");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.