Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new object in JavaScript?

Tags:

javascript

Why is this not working??

    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
like image 724
FatDogMark Avatar asked Dec 04 '12 06:12

FatDogMark


People also ask

How do you create a new object?

Creating an Object Declaration − A variable declaration with a variable name with an object type. Instantiation − The 'new' keyword is used to create the object. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

How do you create a new object in JavaScript Mcq?

Which of the following code creates an object? Explanation: var book = new Object(); will create an object.

How do you create a new object from a class in JavaScript?

To create an object, use the new keyword with Object() constructor, like this: const person = new Object(); Now, to add properties to this object, we have to do something like this: person.

How do I create an object in es6?

The Object() Constructor JavaScript provides a special constructor function called Object() to build the object. The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method.


2 Answers

The syntax:

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

is an object literal. It defines an instance of an object, but not the class that defines it. Therefore, there is no way to "new-up" another instance of the object.

Take a look at jQuery's extend functionality:

var blacksheep = {
}

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

This will copy all the properties of sheep into blacksheep, then merge the third parameter into blacksheep, effectively achieving what you want.

like image 138
armen.shimoon Avatar answered Oct 07 '22 04:10

armen.shimoon


To make another black sheep based on sheep, in this scenario you could do (using jQuery):

var blacksheep = $.extend(sheep, { color: 'black' });
like image 38
Richard Rout Avatar answered Oct 07 '22 03:10

Richard Rout