gpt4 book ai didi

javascript - Node.js/Javascript 通过设置 __proto__ 向现有对象引入方法

转载 作者:搜寻专家 更新时间:2023-11-01 00:45:46 25 4
gpt4 key购买 nike

TL;DR - 是否可以通过设置 __proto__ 属性来实现类似 mixin 的行为?

我有一个对象列表(从一些外部来源获取),它们都具有相同的属性集(比如,_name)。我想向它们中的每一个添加一些常用方法(例如,返回 _name 属性长度的 nameLen())。这是一种方法:

// In reality this list of docs is generated by the DB driver:
var docs = [ { _name: 'some name' }, { _name: 'some other name' } ]

// Now, I want to introduce a method to each doc...
docs.forEach(function(doc) {
doc.nameLen = function() { return this._name.length; }
});

然后我意识到我可以通过设置每个文档的 __proto__ 属性来实现类似的行为:

// In reality this list of docs is generated by the DB driver:
var docs = [ { _name: 'some name' }, { _name: 'some other name' } ]

// Now, I want to introduce a method to each doc...
var myMixin = { nameLen: function() { return this._name.length; } };
docs.forEach(function(doc) {
doc.__proto__ = myMixin; // <-- Use myMixin as the prototype
});

假设我想添加的只是方法而不是声明这似乎是一个更优雅的解决方案:(a) 节省空间; (b) 我稍后可以将方法添加到 myMixin,它们将立即在所有文档中可用。

另一方面,摆弄 __proto__ 似乎有点冒险,但我不确定,因此我的问题是:

通过更改它们的 __proto__ 属性向预先存在的对象引入方法是否安全?

最佳答案

只具有显式类而不是临时内联原型(prototype)更改可能会更好。

var Doc = require( "./doc.js" );

//FIXME configure your driver/schema so that Doc objects
//are returned in the first place
var docs = docs.map(function(v) {
return new Doc(v._name);
});

//Done

文档.js:

module.exports = (function() {
var method = Doc.prototype;

function Doc( name ) {
this._name = name;
}

method.nameLen = function() {
return this._name.length;
};

return Doc;
})();

但是,是的,即使在我看来它不太易于维护,那也是安全的。

关于javascript - Node.js/Javascript 通过设置 __proto__ 向现有对象引入方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18280051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com