您正在寻找constructor概念。
JavaScript 中的所有函数是对象并可用于创建对象:
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
and 如果它被调用new
操作员那么它将返回一个对象,其中包含定义的所有属性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
and make_person_object
是那个呼唤吗new make_person()
(而不是简单地make_person()
) 不会做任何不同的事情...两者都会产生相同的对象。呼唤make_person_object()
没有new
然而,运算符将定义您的this
当前的属性this
对象(一般window
如果您在浏览器中操作。)
Thus:
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 指出的,这种做事方式创建了对prototype
的财产make_person_object
我们创造的每个“人”。这使我们能够在事后向人员添加方法和属性:
// 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
这可能会被误认为是普通函数。
也可以看看:
-
The new操作员
- 鲍宾斯很棒JavaScript 子类化简介(两者都与and没有原型继承。)