Roman
Roman

Reputation: 313

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

Upvotes: 1

Views: 89

Answers (2)

Jai Bhati
Jai Bhati

Reputation: 31

From Google's styleguide for Javascript : You should not add/remove properties outside constructors.

Tip: Properties should never be added to or removed from an instance after the constructor is finished, since it significantly hinders VMs’ ability to optimize. If necessary, fields that are initialized later should be explicitly set to undefined in the constructor to prevent later shape changes. Adding @struct to an object will check that undeclared properties are not added/accessed. Classes have this added by default.

Upvotes: 0

Bergi
Bergi

Reputation: 664484

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.

Upvotes: 0

Related Questions