Search code examples
javascriptooppropertiesprocessing.js

Can I define a property within an object prototype (method)?


Question part 1: I've made an object constructor with properties in it, but I am wondering if I could define another property of the object within one of it's methods. For example:

var Player = function(p1) {
    this.property1 = p1;
    this.property2 = 0;
}

then, can I define this.property3 in a method, like:

Player.prototype.drawMethod = funtion() {
    this.property3 = 1;
}

and have it accessible, like:

var obj = new Player(true);
if (obj.property3 ===1 && obj.property1 === 1) {
    //code
} else {
    obj.property3 = obj.property2;
}

Question part 2: Also, will properties be accepted as functions, and would I call them using the following way:

this.func = function() {
    //code
}
...
obj.func();

Solution

  • I am wondering if I could define another property of the object within one of it's methods

    Yes you can.

    But notice that this is considered bad style, because it's not visible at one single point (the constructor) which properties the instances will have. Also engines are known not to optimise this case - they reserve the necessary space for the shape of object that the constructor creates, and changing this after the instantiation requires some extra work.

    Will properties be accepted as functions, and would I call them [like methods]?

    Yes.