javascript - 如何在 JavaScript 中使用函数构建对象

标签 javascript jquery

I don't think this is an opinion based question as I'm asking for "proper" technique, not "the best" technique or "your favorite" technique. The below options have objective tradeoffs and I'm wondering what the industry-standard approach to handling prototype definitions and function definitions is.

假设我有很多 apple 对象:

var newApple = function(){
   return  {
      id: new guid(),
      color: red
   }
}
var apple = newApple();

我经常吃这些苹果并称之为:

appleManager.eatApple(apple, fast)

但我想这样做:

var newApple = function(){
   return {
      id: new guid(),
      color: red,
      eat: function(speed){
         // a bunch of logic here
      }
}

然后调用

apple.eat(fast);

但在我的脑海中,我想到的是所有这些函数漂浮在周围占用空间,而之前只有一个函数实例。

我还想知道在对象上将 eat 定义为 eatApple(this, speed) 是否是一个更合适的选项 - 这样函数就位于一个地方我们只是从对象中引用它。

关于 javascript 对象的行为特定功能的定义有哪些选项和客观权衡?例子就是花花公子。

最佳答案

这是使用 @Potter 提到的原型(prototype)链的示例。

function Apple(){
    this.id = new guid();
    this.color = 'red';
}

Apple.prototype = {
   eat:function(speed) {
       //do something
   }
}

var apple = new Apple();

apple.eat('fast');
console.log(apple.color);//prints 'red'

Apple 函数是一个构造函数。附加到 this 指针并放入原型(prototype)中的任何内容都将被每个实例“继承”。

在 JavaScript 中,您可以使用原型(prototype)链模拟经典继承。

function Fruit(color) {
    this.color = color;
}

Fruit.prototype = {
    eat:function() {
      console.log('Eating some fruit.');
    }
};

function Apple(color) {
    Fruit.call(this, color);//Call the parent constructor function
    this.isOnATree = true; //Add some new properties
}
Apple.prototype = Object.create(Fruit); //Inherit all parent methods
Apple.prototype.eat = function() { //Override parent eat method
    console.log('Eating a' + this.color + ' apple');
};

var apple = new Apple('red');
apple.eat(); //Eating a red apple.

另外,我会推荐JavaScript the Good Parts .

关于javascript - 如何在 JavaScript 中使用函数构建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44211699/

相关文章:

javascript - 表排序器中的延迟加载图像

javascript - 如何在不影响模板的情况下用 Angular 模拟 REST

javascript - IE中的选择范围

javascript - 如何自定义 jquery ui 自动完成?

jquery - 使用 jquery 在 <p> 标签内插入内容

数组对象中的javascript数组对象

javascript - MVC Javascript 根据复选框值语法切换 TextInputFor Readonly?

javascript - StackOverflow 代码颜色是怎么设置的?

javascript - 无法使用 Link 组件传递状态。为什么状态未定义?

javascript - 获取当前窗口顶部相对于文档正文的位置