JS:在创建工厂函数而不是类时如何创建原型?

时间:2019-01-23 22:01:28

标签: javascript factory

如果我要创建工厂函数,我将如何创建原型以避免新对象的每个实例继承每个属性?

    function Person(name) {
        function indentify() {
           return "I am " + name
        }

        return Object.freeze({
            name,
            indentify

        })

    }

如果我想创建一个Person对象而不让所有对象都包含ID,我可以使用工厂函数来执行此操作,还是必须使用Class语法?

4 个答案:

答案 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函数。