在Javascript中向自定义对象添加方法 [英] Adding methods to custom objects in Javascript

查看:133
本文介绍了在Javascript中向自定义对象添加方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在Javascript中使用'原型'与'这个'?


我访问了各种网站,但无法理解以下向自定义对象添加方法的方法之间的区别:



方法1:

 函数circle(radius){
this.radius = radius;
this.area = function(){return 3.14 * this.radius * this.radius;}
}

方法2:

 功能圈(半径){
this.radius = radius ;
}
circle.prototype.area = function(){return 3.14 * this.radius * this.radius; }

其中一种方法是否有任何性能或设计问题而另一种方法没有?<这是查看区别的一种方法:

  var circle1 = circle(1); 
var circle2 = circle(1);
alert(circle1.area == circle2.area);

对于Method1,当Method2你会看到 false 收益率 true 。这是因为在第一种情况下,你为每个创建的对象分配一个新的闭包函数,两个对象最终会有不同的区域函数,即使它们都做同样的事情。在第二种情况下,对象与 area 方法共享相同的原型对象,该方法在两种情况下当然都是相同的。



通常Method2更好,原因如下:


  1. 对象创建速度更快,因为只需要初始化自定义属性。

  2. 在实例化同一事物的多个副本时,不要浪费内存。

  3. 通过调用<可以轻松找出哪些对象属性具有自定义值code> Object.hasOwnProperty 。

还有一些缺点要记住。


  1. 即使您从未创建任何对象,也总是花时间设置原型。

  2. 属性访问稍微慢一些,因为JavaScript引擎需要先检查对象属性,然后再检查原型对象的属性(现代JavaScript引擎可以很好地优化它)。

  3. re是在原型上放置对象或数组的常见陷阱,它们将在所有对象实例之间共享。

这是一个常见错误的示例:

  function NumberCollection()
{
}
NumberCollection。 prototype = {
numbers:[],
sum:function()
{
var result = 0;
for(var i = 0; i< this.numbers.length; i ++)
result + = this.numbers [i];
返回结果;
}
}

var c1 = new NumberCollection();
c1.numbers.push(5);
alert(c1.sum()); //显示5
var c2 = new NumberCollection();
c2.numbers.push(6);
alert(c2.sum()); //哎呀,显示11因为c1.numbers和c2.numbers是相同的

这里的正确方法将是:

  function NumberCollection()
{
this.numbers = [];
}
NumberCollection.prototype = {
数字:null,
sum:function()
{
var result = 0;
for(var i = 0; i< this.numbers.length; i ++)
result + = this.numbers [i];
返回结果;
}
}


Possible Duplicate:
Use of 'prototype' vs. 'this' in Javascript?

I went to various websites but not able to understand the difference between the following ways of adding methods to custom objects:

Method 1:

function circle(radius){
     this.radius = radius;
     this.area = function(){ return 3.14*this.radius*this.radius;}
}

Method 2:

function circle(radius){
     this.radius = radius;
}
circle.prototype.area = function(){ return 3.14*this.radius*this.radius; }

Are there any performance or design issues that one of the methods has and the other does not?

解决方案

Here is one way to see the difference:

var circle1 = circle(1);
var circle2 = circle(1);
alert(circle1.area == circle2.area);

For Method1 you will see false while Method2 yields in true. That's because in the first case you assign a new closure function to each object created, two objects end up with different area functions even though both do the same thing. In the second case the objects share the same prototype object with its area method, that method is of course identical in both cases.

Usually Method2 is preferable for several reasons:

  1. Object creation is faster because only custom properties need to be initialized.
  2. You don't waste memory on instantiating multiple copies of the same thing.
  3. You can easily find out which of the object properties have custom values by calling Object.hasOwnProperty.

There are some disadvantages as well to keep in mind.

  1. You always spend time on setting up the prototype even if you never create any objects.
  2. Property access is slightly slower because the JavaScript engine needs to check object properties first and then the properties of the prototype object (modern JavaScript engines optimize this pretty well however).
  3. There is a common fall trap of putting objects or arrays on the prototype, these will be shared between all object instances.

Here is an example of the common mistake:

function NumberCollection()
{
}
NumberCollection.prototype = {
    numbers: [],
    sum: function()
    {
        var result = 0;
        for (var i = 0; i < this.numbers.length; i++)
            result += this.numbers[i];
        return result;
    }
}

var c1 = new NumberCollection();
c1.numbers.push(5);
alert(c1.sum());   // Shows 5
var c2 = new NumberCollection();
c2.numbers.push(6);
alert(c2.sum());   // Oops, shows 11 because c1.numbers and c2.numbers is the same

The correct approach here would be:

function NumberCollection()
{
    this.numbers = [];
}
NumberCollection.prototype = {
    numbers: null,
    sum: function()
    {
        var result = 0;
        for (var i = 0; i < this.numbers.length; i++)
            result += this.numbers[i];
        return result;
    }
}

这篇关于在Javascript中向自定义对象添加方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆