sup*_*per 3 javascript function object
我有这样的代码:
function Food(type) {
this.type = type;
this.timesEaten = 0;
}
Food.prototype.eat = function() { // Dependent function
this.timesEaten++;
}
Food.prototype.pasta = function() { // In-dependent function
return new Food("pasta")
}
Run Code Online (Sandbox Code Playgroud)
所以,我希望能够在不定义新食物的情况下使用面食功能,如下所示:
var pasta = Food.pasta()
Run Code Online (Sandbox Code Playgroud)
Buut,这不起作用,你必须这样做:
var pasta = new Food().pasta()
Run Code Online (Sandbox Code Playgroud)
好吧,如果您像这样设置食物,"Food.pasta()"确实有效:
var Food = {
pasta: function() {
return {type: pasta};
}
}
Run Code Online (Sandbox Code Playgroud)
但是新的食物将不起作用,这意味着我将不得不使用"return {type:pasta}".
我想知道,有没有办法创造一种可以既依赖又独立的食物?
function Food(type) {
this.type = type;
this.timesEaten = 0;
}
Food.prototype.eat = function() { // Dependent function
this.timesEaten++;
}
Food.pasta = function() { // In-dependent function
return new Food("pasta")
}
Run Code Online (Sandbox Code Playgroud)
Food.prototype函数仅适用于对象Food,而for Food.pasta Food只是一个名称空间对象.
用法:
Food.pasta();
Run Code Online (Sandbox Code Playgroud)
像您的.pasta()方法那样不对任何实例数据进行操作的方法称为静态方法.您不希望它在原型上,因为原型只会在实例化对象的查找链中(Food通过执行创建实际对象之后new Food()).
相反,对于静态方法,您可以将它放在构造函数本身上,如下所示:
Food.pasta = function() {
return new Food("pasta");
}
Run Code Online (Sandbox Code Playgroud)
你可以这样称呼它:
var pasta = Food.pasta();
Run Code Online (Sandbox Code Playgroud)
记住在javascript中,函数也是对象也是有用的,所以它们可以有属性/方法,当你正在寻找放置静态函数或不属于特定实例化对象或需要调用的数据的地方时一个特定的实例化对象,Constructor对象通常是放置它们的好地方.