What's the Difference of Javascript Object "new" keyword [duplicate] - javascript

This question already has answers here:
Should I be using object literals or constructor functions?
(12 answers)
Javascript Object : Literal Vs Constructor [duplicate]
(2 answers)
Literal notation VS. constructor to create objects in JavaScript [duplicate]
(2 answers)
Closed 5 years ago.
Can someone tell me what is difference between:
function Customer(name, age) {
this.Name = name;
this.Age = age;
}
var cust1 = new Customer('Your Name', 20);
var name1 = cust1.Name;
var age1 = cust1.Age;
and:
function Customer() {
return {
Name: 'Your Name',
Age: 20
}
};
var cust2 = Customer();
var name2 = cust2.Name;
var age2 = cust2.Age;
It produces the same output, after all, but the mechanics are different and I am not sure why.
what's the purpose of "new" in the first one though i could just do this:
var cust1 = Customer('Your Name', 20);
var name1 = cust1.Name;
var age1 = cust1.Age;

The first uses a constructor, the second a factory function.
Constructors are functions that you invoke with the new keyword. Doing so allocates a new object for you and make this a reference to this new object so you can easily mutate it. Constructors are basically syntax sugar that mimics other OOP languages construct to create new objects.
Factories are simple functions that return a plain object. You are in charge of allocating the new object yourself and returning it.
The result is exactly the same at the difference that you can't use instanceof with objects created via a factory function.
Both have pros and cons that get beyond the subject of this question: Constructors vs Factory Methods.

The output is equal (more less) but the code behaves in two different ways
In the first case the 'function' is used as a constructor for a new Js Object
Differently in the second case the 'function' just returns an object.
There isn't a real difference between the two methods but the first is more used and recommended
console.log() the two results in:
constructor: Customer { Name: 'Your Name', Age: 20 }
return obj: { Name: 'Your Name', Age: 20 }

Related

JavaScript - How to set new instance as parameter, created dynamically? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 7 years ago.
I have a method which sets a new instance to an array, created dynamically. How can I do that without the use of eval()?
var Form = (function(){
function Form(params){
this.shapesArray = [];
this.shape;
...
}
Form.prototype.submit = function(){
... this.shape is the shape selected by the user ...
this.setShape('new Shapes.' + this.shape + '(arg1, arg2, color)');
}
Form.prototype.setShape = function(obj){
this.shapesArray.push(obj);
}
return Form;
}());
So, how to call the setShape method by passing new instance to it without eval()?
This works so far:
Form.prototype.submit = function(){
eval('this.setShape(new Shapes.'+ this.shape.capitalize() +'('+ str_params + '))');
}
But using eval() is not a good practice. How to achieve the same result wighout eval()?
You may use the bracket notation to access the property :
this.setShape(new Shapes[this.shape](arg1, arg2, color));
Now, if you get your arguments from a dynamic array, it's a little more complex because you can't just use apply.
Here's a solution:
var constructor = new Shapes[this.shape];
var C = function(){
return constructor.apply(this, arr_of_args);
}
C.prototype = constructor.prototype;
this.setShape(new C());
But this starts to get tricky and hard to read. A new design of your application not involving dynamic constructors having a variable number of arguments might be preferable.

why the values of properties in the prototype are inconsistent? [duplicate]

This question already has an answer here:
JavaScript: instanceof operator
(1 answer)
Closed 8 years ago.
I called console.log(Family.prototype.money) and value is 200, which confirms that asset is the prototype of the function Family. But when I called console.log(other.money), the value is 1000, which I assigned before to the prototype. What is wrong here? It looks like the prototype of the object other is different from that of the function Family, which totally contradicts with what I read from the book Object-Oriented Javascript.
function Family(father, mother, children){
this.father = father,
this.mother = mother,
this.children = children,
this.num = function(){
return (this.children.length+2);
}
}
Family.prototype.money = 1000; // notice!!!!
var myFamily = new Family('Hung', 'Hong', ['Phuong', 'Lien', 'Hiep']);
var other = new myFamily.constructor('Lan', 'Linh', ['Tung']);
var money = other.money;
var asset = {
money: 200,
car: 2,
house: 10
}
Family.prototype = asset;
The prototype of a function is not the actual prototype of the instance object. When you use new the prototype object is used as a template for the internal [[Prototype]] property, exposed in some browsers as __proto__. So before you change the prototype this expression is true:
Family.prototype === other.__proto__ // true
Family.prototype = asset;
And after you chnge it, it is false:
Family.prototype = asset;
Family.prototype === other.__proto__ // false

What does it mean to add a prototype to a function? [duplicate]

This question already has answers here:
How does JavaScript .prototype work?
(26 answers)
Closed 8 years ago.
Given:
var x = function () {
};
x.prototype = { abc: 25 };
Can someone explain to me what this means. Could this be done all inside a function without the .prototype?
var x = function () {
// something here ?
};
Prototypes are how the class model works in JavaScript - you've created a class x that has a property abc which defaults to 25:
var obj = new x();
alert(obj.abc); // 25
The function x is the class constructor, it is called when a new instance of that class is created and can initialize it. And that means of course that you can just set the abc property there:
var x = function()
{
this.abc = 25;
};
var obj = new x();
alert(obj.abc); // 25
This is supposedly the less efficient approach however:
You have to manipulate each object created rather than setting the property on the prototype once and forever.
The property is stored on each object and consumes memory each time, as opposed to being stored once on the prototype.
ECMAScript Harmony has a nicer syntax for defining classes and prototypes, however this one isn't implemented in any browser yet:
class x {
constructor() {
...
}
public abc = 25;
}
This is equivalent to your code defining the prototype, merely grouping related operations a little better.

Difference between "{}" and "new Object()" [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
creating objects - new object or object literal notation?
What exactly is the difference between the following:
var myData = new Object();
myData["name"] = "ATOzTOA";
myData["site"] = "atoztoa";
and
var myData = {};
myData["name"] = "ATOzTOA";
myData["site"] = "atoztoa";
Update
What I got is this...
var myData = {
"name" : "ATOzTOA",
"site" : "atoztoa",
};
is a shortcut to
var myData = new Object({
"name" : "ATOzTOA",
"site" : "atoztoa",
});
Am I right?
There is no difference (technically). {} is just a shortcut for new Object().
However, if you assign an object literal, you may directly form a new object with multiple properties.
var myData = {
name: 'ATOzTOA',
size: 'atoztoa'
};
..which might feel more convenient. Also, it reduces the access on the object and is ultimately faster. But that is about microoptimizations. More important is that its a lot less to type.
Nothing. {} just a short hand for new Object()
Its same logic as your full name is 'Mark Zuckerberg' and people call you ' Hi Mark'
No difference in my view , Both are initializing the object. nothing else , it is a shortcut.

javascript object declaration using prototype(including case) [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Use of 'prototype' vs. 'this' in Javascript?
I donot know why some developer use javascript prototype object exactly.
so, I made a sample code below.
one using prototype object, the other plain syntax.
what is difference btwn two of them?
Is there any benefit to use prototype syntax, the first case?
Car.prototype.engine_ = 'bmw';
Car.prototype.getEngine = function(){
return this.engine_;
}
Car.prototype.setEngine = function(engine){
this.engine_ = engine;
}
function Car(){
//....
}
var myCar = new Car();
myCar.getEngine();
myCar.setEngine('benz');
console.debug(myCar.getEngine());
vs
function Car(){
this.engine_ = 'bmw';
this.setEngine = function(engine){
engine_ = engine;
}
this.getEngine = function() {
return engine_;
}
//...
}
var myCar = new Car();
myCar.getEngine();
myCar.setEngine('benz');
console.debug(myCar.getEngine());
Yes, there is a difference. Using prototype, your property or method is declared once in the Object and the same for all instances. Using direct properties/methods, these properties and method are added to every instance of the Object. So here's your Car constructor:
function Car(){this.engine = 'no known engine'};
Car.prototype.setEngine = function(val){
this.engine = val;
}
Now the method setEngine is equal to all instances of your Car, but the engine property can vary per instance. The prototypal methods are defined once and looked up via the prototype chain (see also this). In this case setEngine sets the 'engine' property of the current instance of your Car. So you can do:
var bmw = new Car, merc = new Car;
bmw.setEngine('BMW');
merc.setEngine('Mercedes');
console.log(bmw.engine); //=> 'BMW'
console.log(merc.engine); //= 'Mercedes'
AFAIK there is no difference between this ones

Categories