我可以在对象原型(方法)中定义属性吗? [英] Can I define a property within an object prototype (method)?

查看:54
本文介绍了我可以在对象原型(方法)中定义属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题第 1 部分:我已经创建了一个带有属性的对象构造函数,但我想知道是否可以在其中一个方法中定义对象的另一个属性.例如:

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

那么,我可以在一个方法中定义this.property3,比如:

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

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

并使其可访问,例如:

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

问题第 2 部分:此外,属性是否会被接受为函数,我是否会使用以下方式调用它们:

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

推荐答案

我想知道是否可以在其中一个方法中定义对象的另一个属性

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

是的,你可以.

但是请注意,这被认为是不好的样式,因为它在单个点(构造函数)上是不可见的,实例将具有哪些属性.众所周知,引擎不会优化这种情况 - 它们为构造函数创建的对象形状保留了必要的空间,并且在实例化之后更改它需要一些额外的工作.

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]?

是的.

这篇关于我可以在对象原型(方法)中定义属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆