原型(prototype)化为数组的 Javascript 对象成员被所有类实例共享

标签 javascript arrays oop class prototype

以前有没有人注意到这种行为?这真的让我大吃一惊……我本来希望原型(prototype)数组对每个类实例都是私有(private)的,而不是在所有类实例之间共享。

有人可以验证这是正确的行为并可能更详细地解释这种行为吗?

注意注释代码以及它如何影响脚本的行为。

<html>
<head>

<script type="text/javascript">

function print_r( title, object ) {

    var output = '';
    for( var key in object ) {

        output += key + ": " + object[ key ] + "\n";

    }

    output = title + "\n\n" + output;

    alert( output );

}

function Sandwich() {

    // Uncomment this to fix the problem
    //this.ingredients = [];

}

Sandwich.prototype = {

    "ingredients" : [],
    "addIngredients" : function( ingArray ) {

        for( var key in ingArray ) {

            this.addIngredient( ingArray[ key ] );

        }

    },
    "addIngredient" : function( thing ) {

        this.ingredients.push( thing );

    }

}

var cheeseburger = new Sandwich();
cheeseburger.addIngredients( [ "burger", "cheese" ] );

var blt = new Sandwich();
blt.addIngredients( [ "bacon", "lettuce", "tomato" ] );

var spicy_chicken_sandwich = new Sandwich();
spicy_chicken_sandwich.addIngredients( [ "spicy chicken pattie", "lettuce", "tomato", "honey dijon mayo", "love" ] );

var onLoad = function() {

    print_r( "Cheeseburger contains:", cheeseburger.ingredients );

};

</script>

</head>
<body onload="onLoad();">
</body>
</html>

非常感谢。

最佳答案

对象的原型(prototype)只是一个对象。原型(prototype)属性在从该对象继承的所有对象之间共享。如果您创建“类”的新实例(JS 中不存在类),即从原型(prototype)继承的对象,则不会复制属性。

它只会影响您如何使用这些继承的属性:

function Foo() {}

Foo.prototype = {
    array: [],
    func: function() {}
}

a = new Foo();
b = new Foo();

a.array.push('bar');
console.log(b.array); // prints ["bar"]

b.func.bar = 'baz';
console.log(a.func.bar); // prints baz

在所有这些情况下,您总是在使用同一个对象。

但是,如果您为对象的属性分配值,则该属性将在对象本身而不是其原型(prototype)上设置/创建,因此不共享:
console.log(a.hasOwnProperty('array')); // prints false
console.log(a.array); // prints ["bar"]
a.array = ['foo'];
console.log(a.hasOwnProperty('array')); // prints true
console.log(a.array); // prints ["foo"]
console.log(b.array); // prints ["bar"]

如果要为每个实例创建自己的数组,则必须在构造函数中定义它:
function Foo() {
    this.array = [];
}

因为在这里,thisnew调用 new Foo() 时生成的对象.

经验法则是:实例 - 特定数据应该分配给构造函数内的实例,共享 数据(如方法)应分配给原型(prototype)。

您可能想阅读 Details of the object model它描述了基于类与基于原型(prototype)的语言之间的差异以及对象的实际工作方式。

更新:

您可以通过 Object.getPrototypeOf(obj) 访问对象的原型(prototype)(可能无法在非常旧的浏览器中使用)和 Object.getPrototypeOf(a) === Object.getPrototypeOf(b)给你true .它是同一个对象,也称为 Foo.prototype .

关于原型(prototype)化为数组的 Javascript 对象成员被所有类实例共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4425318/

相关文章:

Javascript按数组对对象数组进行排序

javascript - 如何通过字符差异作为分隔符来拆分字符串?

.net - 空对象模式值得吗?

javascript - 更换干草堆中不精确的针

javascript - 来自 API 的 node.js pg-promise 和分页

ruby-on-rails - 如何在没有根 key 的情况下解析 JSON

java - 如何在java中编写组合和聚合

oop - 如何在不可变抽象基类的默认方法中实例化子类?

javascript - 如何引用与 HTML 和 jQuery 一起使用的 XML 文件/数据?

javascript - 如何使用正则表达式搜索字符串并仅更改其中的一部分?