gpt4 book ai didi

javascript - 向原型(prototype)添加方法时的范围困难

转载 作者:行者123 更新时间:2023-12-03 04:12:14 25 4
gpt4 key购买 nike

我想创建一个工厂来生产函数构造函数作为产品。工厂拥有向产品原型(prototype)添加方法的方法。实例化的产品拥有这些用于访问产品文档字段的函数。

https://jsfiddle.net/84fzwvj7/2/

function Factory() {
this.Product = function(doc = {}) {
this.doc = doc;
}
}

Factory.prototype.addDocField = function(name) {
this.Product.prototype["set" + name] = function(value) {
this.doc[name] = value;
}
this.Product.prototype["get" + name] = function() {
return this.doc[name];
}
return this;
}

var MyClass = new Factory().addDocField("Test").Product;
var obj = new MyClass();
console.dir(obj.doc.Test); // undefined
obj.setTest("Lorem Ipsum");
console.dir(obj.doc.Test); // "Lorem Ipsum"

此方法适用于仅需要 getter/setter 的文档字段。但我需要更复杂的字段访问器,如下所示:

// ... Object was created before with an array like field
obj.users.create(login);
obj.users.deleteById("46891");

遗憾的是,我无法找到定义 createdeleteById 函数并将其 this 关键字绑定(bind)到 的方法对象。我尝试将原型(prototype)方法添加到对象中,但这就是我无法弄清楚如何使我的范围正确的地方:

https://jsfiddle.net/5n5pachh/3/

Factory.prototype.addUserField = function(name) {
this.Product.prototype[name] = {};

// Using a classic function does not work because ...
this.Product.prototype[name].create = function(login) {
console.dir(this); // ... 'this' is bound to this.Product.prototype[name]
}

// Using an arrow function does not work because ...
this.Product.prototype[name].create = function(login) {
console.dir(this); // ... 'this' is bound to Factory.prototype.addUserField
}

// None of the above functions work how I want them to, because they can't
// access the products doc field (i.e.: this.doc)

return this;
}

(如何)是否可以将 createdeleteById 函数的 this 关键字绑定(bind)到我的 obj实例?

最佳答案

您只需要使用 bindthis 作用域绑定(bind)到您的函数上。如果我理解你想要 this 来表示 this 只是意味着将 .bind(this.Product); 标记到函数的末尾:

this.Product.prototype[name].create = function(login) {
console.dir(this);
}.bind(this.Product);

但我认为这并不能完全解决您的问题 - 当您调用 addUserField 时,还没有 Product 实例可供您绑定(bind)。因此,您从上面得到的是 this 引用 Product 的定义,而不是带有 doc 的实例。为此,您需要重构您的代码。

这是一个解决方案,它更改您的工厂以实际创建 Product 的实例,与您的不太一样,但希望满足相同的要求

function Factory() {

this.createProduct = function(doc){
var product = {doc:doc};
userFields.forEach(function(uf){
product[uf.name] = {};
product[uf.name].create = uf.create.bind(product) ;
})
return product;
}

var userFields = [];
this.addUserField = function(name){
userFields.push({
name: name,
create: function(login){
console.dir(this.doc);
}
}) ;
return this;
}
}



// Use case
var obj = new Factory().addUserField("users").createProduct({foo:"bar"});
console.log(obj.doc)
obj.users.create();

关于javascript - 向原型(prototype)添加方法时的范围困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44279871/

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