你能把一个函数当作一个对象来调用吗?例如:
function Tip(txt){
this.content = txt;
this.shown = false;
}
和:
var tip = new Tip(elem.attr('title'));
我的问题:
- 你能为函数调用
new
吗? - “this”的使用成为可能,因为我们使用那个函数作为一个对象?
最佳答案
您正在寻找 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}
但是,为了创建特定类型的新对象(也就是说,继承原型(prototype)、具有构造函数等),函数可以引用 this
和 if它使用 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
和 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 指出的那样,这种做事方式会在我们创建的每个“人”上创建对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
。
另请参阅:
- The
new
operator - bobince 很棒 introduction to subclassing in JavaScript (和都没有原型(prototype)继承。)
关于javascript : function and object. ..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5958417/