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

℡╲_俬逩灬. 提交于 2021-02-05 09:10:28

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/37668729/can-i-define-a-property-within-an-object-prototype-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!