DarkLightA
DarkLightA

Reputation: 15652

Why doesn't this javascript code work?

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

Upvotes: 0

Views: 79

Answers (4)

Jacob Relkin
Jacob Relkin

Reputation: 163228

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"

Upvotes: 4

Álvaro González
Álvaro González

Reputation: 146350

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");

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382616

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);

Upvotes: 3

Quentin
Quentin

Reputation: 943108

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);

Upvotes: 3

Related Questions