如果我要创建工厂函数,我将如何创建原型以避免新对象的每个实例继承每个属性?
function Person(name) {
function indentify() {
return "I am " + name
}
return Object.freeze({
name,
indentify
})
}
如果我想创建一个Person对象而不让所有对象都包含ID,我可以使用工厂函数来执行此操作,还是必须使用Class语法?
答案 0 :(得分:1)
如果要继续使用工厂功能并避免使用new
运算符,则可以使用Object.create
创建具有特定原型的对象:
const personProto = {
identify() {
return "I am " + this.name; // needs to access the property of course, there's no closure
}
};
function Person(name) {
return Object.freeze(Object.assign(Object.create(personProto), {name}));
}
答案 1 :(得分:0)
function Person(name) {
this.name = name;
}
Person.prototype.indentify = function() {
return "I am " + this.name
}
离题,我猜你在找identify
这个词吗?
答案 2 :(得分:0)
我将使构造函数起作用,并向原型添加标识,如下所示:
EmbeddedKafkaBroker
并像这样创建一个新人
function Person(name) {
this.name = name;
Object.freeze(this)
}
Person.prototype.indentify = function() {
return "I am " + this.name
}
答案 3 :(得分:-1)
如何将功能组合到人身上。一个例子可能是这样的:
const createPerson = (name) => ({ name })
const withIdentify = (person) => ({ ...person, identify: () => `I am ${person.name}` })
let person = createPerson('Chris')
console.log(person) // { name: 'Chris' }
person = withIdentify(person);
console.log(person) // { name: 'Chris', identify: f }
console.log(person.identify()) // 'I am Chris'
如果您决定的话,甚至可以使用部分执行来清理withIdentify
函数。