Pat*_*ick 6 javascript constructor function
function catRecord(name, birthdate, mother) {
return {name: name, birth: birthdate, mother: mother};
}
Run Code Online (Sandbox Code Playgroud)
我对构造函数的理解是一个用来构建对象的函数.
这个catRecord函数会算作构造函数吗?
不,您给出的函数返回一个没有类型信息的新关联数组。您所追求的构造函数是这样的:
function fixedCatRecord(name, birthdate, mother) {
this.name = name;
this.birthdate = birthdate;
this.mother = mother;
}
Run Code Online (Sandbox Code Playgroud)
这样,您将拥有一个知道它是fixedCatRecord的对象,这意味着它可以访问所有适当的元数据(例如知道可以调用它的方法)。
请注意,它们都可以与“new”一起使用,但它将是 Object 类型的对象(这是关联数组的默认值),而不是catRecord 类型的对象。
例如,如果您正在使用某些东西(例如 Chrome),其中 console.log 提供类型信息:
// this is an Object, not what you want!
console.log(new catRecord("Fluffy", "12/12/12", "Melody"));
// this is a fixedCatRecord, good!
console.log(new fixedCatRecord("Fluffy", "12/12/12", "Melody"));
Run Code Online (Sandbox Code Playgroud)