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
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.
Which of the following code creates an object? Explanation: var book = new Object(); will create an object.
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.
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.
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.
To make another black sheep based on sheep, in this scenario you could do (using jQuery):
var blacksheep = $.extend(sheep, { color: 'black' });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With