如何在JavaScript中创建新对象?

时间:2012-12-04 06:40:16

标签: javascript

为什么这不起作用?

    var sheep = function(options){
        this.options = {sizes: 100,
                        eat: 100,
                 colors: 'white', 
                 running: function () {
                     return this.sizes + this.eat;
                 }
          }
    };

    var blacksheep = new sheep({colors:'black'});       

    alert('blackcsheep color is ' + blacksheep.colors);//error undefined
    alert('blackcsheep color is ' + blacksheep.options.colors);// it return white
    alert('blackcsheep running is ' + blacksheep.running());//error

7 个答案:

答案 0 :(得分:3)

语法:

var sheep = {sizes:100, eat:100, colors:'white',running:function(){
        return this.sizes+this.eat;
        }
    };

是一个对象文字。它定义了一个对象的实例,但不定义了它的类。因此,没有办法“新建”对象的另一个实例。

看一下jQuery的extend功能:

var blacksheep = {
}

$.extend(blacksheep, sheep, { color: black });

这会将sheep的所有属性复制到blacksheep,然后将第三个参数合并到blacksheep,从而有效地实现您的目标。

答案 1 :(得分:1)

要制作另一只基于绵羊的黑羊,在这种情况下你可以做(​​使用jQuery):

var blacksheep = $.extend(sheep, { color: 'black' });

答案 2 :(得分:1)

您可以像这样创建一个绵羊对象。

 function Sheep(sizes,eat,colors){
    this.sizes = sizes;
    this.eat = eat;
    this.colors = colors;
    this.running = function (){
     return this.sizes+this.eat;
    }

    }

或者你也可以像这样写

 function Sheep(sizes,eat,colors){
    this.sizes = sizes;
    this.eat = eat;
    this.colors = colors;        
    }
 sheep.prototype.running = function(){
 return this.sizes + this.eat;    
}

var sheep1 =新羊('100','100','白');

答案 3 :(得分:1)

var sheep = function(){
    this.sizes = 100;
    this.eat = 100;
    this.colors = 'white';
    this.running = function(){
        return this.sizers + this.eat;
    }
}

答案 4 :(得分:1)

您不能像在强类型语言中那样在JavaScript中声明对象。您可以使用以下函数声明对象:

function sheep() {
    this.color = "white";
    this.size = 200;
    this.speed = 100;
    this.running = function () {
        return "the sheep is running!";
    };
}

var blacksheep = new sheep();

alert('sheep size is ' + blacksheep.size);
alert('sheep running is ' + blacksheep.running());​

您的新对象不起作用,因为您正在创建一个名为options的子对象的新对象。 options包含您的所有方法。因此,只有这三行中的第二行才能给出正确答案:

alert('blackcsheep color is ' + blacksheep.colors);
alert('blackcsheep color is ' + blacksheep.options.colors); // Only this one correctly references `options`.
alert('blackcsheep running is ' + blacksheep.running());

答案 5 :(得分:0)

在你的情况下,羊已经是一个无法创建对象对象的对象。 您可以直接将该对象与属性一起使用。

但我认为你想要这样的东西

  

var sheep = {sizes:100,吃:100,颜色:'white',running:function(){               return this.sizes + this.eat;               }           }; Object.defineProperty(sheep,'colors',{value:'black'                                                ,writable:true});

由于

答案 6 :(得分:-1)

Javascript是基于原型而不是基于类的。它不使用类,也是面向对象的。

var whitesheep =new sheep("100","100","white","running");
var blacksheep =new sheep("100","100","black","running");