javascript - 原型(prototype)中的数组和对象 - 不被视为引用

标签 javascript arrays node.js reference

我在 Javascript 中有一个原型(prototype)对象,当我初始化原型(prototype)的新实例并更新原型(prototype)中的属性时,它会更新所有元素。我知道数组和对象是通过引用传递的,想知道可以解决这个问题的解决方案吗?

let Test = function () {}

Test.prototype = {
    array: [],
    add: function (value) {
        this.array.push(value)
    }
}

let test1 = new Test();
let test2 = new Test();

test1.add(1);
test1.add(2);

// Prints [1, 2]
console.log(test2.array);

一个解决方案是:

class Test {

    constructor() {
        this.array = []
    }

    add(value) {
        this.array.push(value)
    }
}

let test1 = new Test();
let test2 = new Test();

test1.add(1);
test1.add(2);

// Prints []
console.log(test2.array);

但我不是在寻找 ES6 方法,而是更“原生”的 javascript。

感谢您的帮助!

最佳答案

事情就是这样:它们视为引用。

当你这样做时:

Test.prototype = {
    array: [], // <- This creates a new array and it's being used in all instances
    add: function (value) {
        this.array.push(value)
    }
}

您想要的是为不同的类实例获取不同的数组实例。在这种情况下,只需在构造函数中执行 this.array = [] 即可:

let Test = function () { this.array = []; }

let Test = function () { this.array = []; }

Test.prototype = {
    array: [],
    add: function (value) {
        this.array.push(value)
    }
}

let test1 = new Test();
let test2 = new Test();

test1.add(1);
test1.add(2);

console.log(test1.array);
// => [1, 2]

console.log(test2.array);
// => []

关于javascript - 原型(prototype)中的数组和对象 - 不被视为引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40485121/

相关文章:

javascript - 如何在nodejs express中的所有http请求中使用中间件

JavaScript - 将对象数组中的属性识别为数组

html - 如何使用 Angular 访问 HTML 中的 JSON 数组对象?

node.js - 如何以非 root 用户身份运行 node.js?

javascript - 如何在 Node 中运行子进程并处理错误

javascript - 为什么 ng-bind-html 只显示文本而不显示链接?

javascript - 每次调用 AJAX 时如何修改 PHP 变量

javascript - 我如何使用带有原始数据而不是图像的 createImageBitmap 作为输入

arrays - 为什么我的 For 循环在 EJS Node js 中只返回一个值?

node.js - 错误: Cannot find module './formats' when deploying node app on heroku server