为什么实例方法在原型中定义,而实例字段在构造函数中定义? [英] Why are instance methods defined in the prototype but instance fields are defined in the constructor?

查看:57
本文介绍了为什么实例方法在原型中定义,而实例字段在构造函数中定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中进行继承时,我经常看到的模式在原型中定义了实例方法,但在构造函数中定义了实例字段(请参见下面的示例).这样做的动机是什么?为什么不保持一致,并在原型中同时定义两者?

When doing inheritance in JavaScript, the pattern that I always see defines instance methods in the prototype, but instance fields in the constructor (see example below). What is the motivation for this? Why not be consistent and define both in the prototype?

function MyClass() {
    this.myField = 0; // why this...
}
MyClass.prototype.myField = 0; // ...instead of this?

推荐答案

说明

因为原型属性在所有实例之间共享,因为每个实例都引用相同的原型对象.

Explanation

Because prototype properties are shared between all instances as every instance has a reference to the same prototype object.

这不是不可变类型的问题,您可以这样做:

This is not an issue with immutable types, you could do:

MyClass.prototype.myField = 0;

var a = new MyClass();
a.myField = 42;

,只有 a 具有此值.这是因为分配为 a 创建了属性 myField .您可以在分配之前和之后通过调用 a.hasOwnProperty('myField')进行测试.

and only a would have this value. This is because the assignment creates the property myField for a. You can test this with calling a.hasOwnProperty('myField') before and after the assignment.

但是,如果您有对象或数组

But if you have objects or arrays

MyClass.prototype.myField = [];

,您只需追加到该数组,而不分配新数组(例如 a.myField = [] ),则每个实例在其中具有新值该数组.

and you just append to that array and don't assign a new array (like a.myField = []), then every instance has the new value in that array.

您必须在构造函数中初始化数组和对象,以便每个实例都具有自己的对象或数组实例.一些样式准则建议您仍在原型上创建属性,但使用 null 对其进行初始化.除了在代码中添加一些概念性结构(如果存在这样的单词)之外,这没有其他好处.

You have to initialize arrays and objects in the constructor, so that each instance gets its own object or array instance. Some style guidelines propose that you still create the property on the prototype, but initialize it with null. This has no benefit other than adding some conceptual structure (if such a word exists) to your code.

例如:

function MyClass() {
    this.myField = [];
}

/**
 * @type {Array}
 */
MyClass.prototype.myField = null;

这篇关于为什么实例方法在原型中定义,而实例字段在构造函数中定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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