2017-05-27 53 views
0

与功能的对象,我不认为这是一个基于观点的问题,我所要求的 “正确”的技术,而不是“最好的”技术或“您最喜欢的” 技术。下面的选项有客观的权衡,我想知道什么是行业标准的方法来处理定义和函数定义原型 是。如何建立在JavaScript

说我有很多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); 

但在我的脑海里,我想所有这些functions漂浮占用空间的,而在此之前有功能的只有一个实例。

我也想知道如果在对象上定义eat作为eatApple(this, speed)将是一个更合适的选项 - 这种方式函数在一个地方,我们只是从对象中引用它。

关于JavaScript对象上行为特定功能的定义,有哪些选择和客观折衷?例子将是花花公子。

+2

你需要寻找到被称为原型继承什么。您将把Apple对象的任何实例方法放到一个名为原型的对象上。新的es6类语法使得它非常简洁。 – Potter

回答

2

下面是一个使用原型链作为@Potter提到的例子。

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指针并放入原型的东西都会被每个实例“继承”。

在JavaScript中,您可以模拟原型链的经典继承。我想推荐JavaScript the Good Parts

1

你可以在原型对象上定义你的函数。这样,你的功能将被放置在一个中心位置,你不会消耗更多的内存。

function Person(first, last, age, eyecolor) { 
this.firstName = first; 
this.lastName = last; 
this.age = age; 
this.eyeColor = eyecolor; 

} 

Person.prototype.name = function() { 
    return this.firstName + " " + this.lastName; 

}; 
0
<!DOCTYPE html> 
<html> 
<body> 

<p>Creating and using an object method.</p> 

<p>An object method is a function definition, stored as a property value.</p> 

<p id="demo"></p> 

<script> 
var person = { 
    firstName: "John", 
    lastName : "Doe", 
    id  : 5566, 
    fullName : function() { 
     return this.firstName + " " + this.lastName; 
    } 
}; 

document.getElementById("demo").innerHTML = person.fullName(); 
</script> 
</body> 
</html> 

May be you can use this script.