您正在寻找constructor 的概念。
JavaScript 中的所有函数are objects 并可用于创建对象:
function make_person(firstname, lastname, age) {
person = {};
person.firstname = firstname;
person.lastname = lastname;
person.age = age;
return person;
}
make_person("Joe", "Smith", 23);
// {firstname: "Joe", lastname: "Smith", age: 23}
但是,为了创建特定类型的新对象(也就是说,继承原型、具有构造函数等),函数可以引用 this 并且 如果使用new operator 然后它将返回一个对象,该对象具有函数中 this 上定义的所有属性 - 在这种情况下 this 引用我们正在创建的新对象。
function make_person_object(firstname, lastname, age) {
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
// Note, we did not include a return statement
}
make_person 和make_person_object 之间需要注意的主要区别是调用new make_person()(而不是简单地make_person())不会做任何不同的事情......两者都会产生相同的对象。但是,在没有 new 运算符的情况下调用 make_person_object() 将在当前 this 对象上定义您的 this 属性(如果您在浏览器中操作,通常是 window。)
因此:
var Joe = make_person_object("Joe", "Smith", 23);
console.log(Joe); // undefined
console.log(window.firstname) // "Joe" (oops)
var John = new make_person_object("John", "Smith", 45);
console.log(John); // {firstname: "John", lastname: "Smith", age: 45}
此外,正如@RobG 指出的那样,这种做事方式会在我们创建的每个“Person”上创建对make_person_object 的prototype 属性的引用。这使我们能够在事后向人员添加方法和属性:
// Assuming all that came before
make_person_object.prototype.full_name = "N/A";
make_person_object.prototype.greet = function(){
console.log("Hello! I'm", this.full_name, "Call me", this.firstname);
};
John.full_name // "N/A"
John.full_name = "John Smith";
make_person_object.full_name // Still "N/A"
John.greet(); // "Hello! I'm John Smith Call me John"
约定像 make_person_object 这样的构造函数是大写、单数和“名词”(因为没有更好的术语)——因此我们将有一个 Person 构造函数,而不是 make_person_object 这可能是被误认为是普通函数。
另见: