Marcio Mazzucato
Marcio Mazzucato

Reputation: 9295

Getting 'undefined' when a property is initialized in the constructor of a prototype

I started to use prototype and i got the expected result if i use the code:

$(document).ready(function() {
    var MyObject = new MyClass();

    MyObject.assign();

    MyObject.console();
});

function MyClass() {
    var myProperty;
};

MyClass.prototype = {

    assign: function() {
        this.myProperty = 'Hello world!';
    },

    console: function() {
        console.log(this.myProperty); // Shows 'Hello world!'
    }
};

But the below code returns undefined. I am not understanding why, can anyone help me please?

$(document).ready(function() {
    var MyObject = new MyClass();

    MyObject.console();
});

function MyClass() {
    var myProperty = 'Hello world!';
};

MyClass.prototype = {

    console: function() {
        console.log(this.myProperty); // Shows 'undefined'
    }
};

Upvotes: 1

Views: 60

Answers (2)

Don Rhummy
Don Rhummy

Reputation: 25820

In the first piece of code, you actually create and define that property: this.myProperty = 'Hello world!'; Before that, this property doesn't exist.

In the second piece of code, you never define the property.

Change it to:

function MyClass() {
    //NOT "var", but "this."
    this.myProperty = 'Hello world!';
};

Another way to do this (if the value to myProperty should default to some value, is to put it in the prototype:

MyClass.prototype = {

    //Now all instantiations will have this preset    
    myProperty: "Hello World",

    console: function() {
        console.log(this.myProperty);
    }
};

Upvotes: 5

Giannis Grivas
Giannis Grivas

Reputation: 3412

Try this :http://jsfiddle.net/csdtesting/d369Lw0f/

According to this about objects and prototype.

$(document).ready(function() {
  var MyObject = new MyClass();
  MyObject.console();
});

function MyClass() {
  this.myProperty = 'Hello world!';
};

MyClass.prototype.console = function() {
    //console.log(this.myProperty);
    document.write(this.myProperty);   
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Hope it helps!

Upvotes: -1

Related Questions