This question already has answers here:
Should I be using object literals or constructor functions?
(12 answers)
Closed 5 years ago.
I recently came across constructors for creating multiple objects with the same properties and methods.
Method 1:
function Person(name) {
this.name = name;
}
And then you can instantiate it like so:
var bob = new Person("bob");
What i would like to know is there a difference between using the standard constructor method and just returning an object inside a function like so:
Method 2:
function Person(name) {
var obj = {
name: name,
};
return obj;
}
I am still able to create multiple objects using the same function. I am just slightly confused on why you would use 'Method 1'? Is it because i can extend the first method using the prototype property? Am i able to extend and create more methods using 'Method 2'?
Am i right in thinking this is why you use constructors because they are more flexible and can be added to and modified whereas the Object literal type inside a function cannot? Also what other benefits does it bring?
Sorry if this is a silly question.
Thanks, any information would be nice
Consider:
function Person(name) { /* either of your approaches */}
Person.prototype.getName = function() {
return this.name;
}
Method 1 will work as expected, method 2 will not, if you call:
new Person('Bob').getName ()
Related
This question already has answers here:
Javascript when to use prototypes
(6 answers)
Use of 'prototype' vs. 'this' in JavaScript?
(15 answers)
Closed 4 years ago.
why should i use prototypes is js?
for example if i want to create a constructor like:
var Person = function(name, yearOfBirth){
this.name = name;
this.yearOfBirth = yearOfBirth;
this.calculateAge = function(){
console.log(2018-this.yearOfBirth);
}
}
is better to use prototype for functions like:
var Person = function(name, yearOfBirth){
this.name = name;
this.yearOfBirth = yearOfBirth;
}
Person.prototype.calculateAge = function(){
console.log(2018-this.yearOfBirth);
}
should i use prototype also for props like name etc?
Can someone tell me the differences between using or not prototypes and what's the best use of it?
Thanks
EDIT: this is the best answer that i've found: https://hackernoon.com/prototypes-in-javascript-5bba2990e04b
Prototype properties are shared across all instances of the constructor function.
In your case the calculateAge function need not be required as a separate instance for all objects that you create out of Person and hence can be moved to Prototype, whereas properties like name and yearOfBirth need a separate instance for each object that you create from Person
You can define Prototypes properties on constructor functions when you wish to create a common property shared across all instances of the function.
This question already has answers here:
Function and Object Javascript
(2 answers)
Closed 5 years ago.
In Javascript, we have two fundamental building blocks called functions and objects. But I'm a bit confused about the phrase functions are special type of objects. Anyways, in Javascript:
We create functions like this:
function foo(){}
Now the above declared function also behaves like an object as below:
foo.staticMethod = function(){}
Ok. I understand it.
Now similarly we create objects like this:
var obj = new Object() // Not using object literal here
That means, we need a function constructor Object to make even an empty object.
But Functions are also objects. How????
So my simple question is, if Object is used to create any new object, then how it can be an object itself as it accepts a property Object.prototype or I should say how a function can be an object ?
function Object(){
return {};
}
This question already has answers here:
Constructor function vs Factory functions
(8 answers)
Closed 5 years ago.
I'm learning javascript and I'm confused with this definition.
I look up in ECMA and it defines constructor as
function object that creates and initializes obejects.
So, can any function object be called constructor?
In js its common to call a function constructor if its aim is to be called with the new operator:
var me = new Human;//Human is a constructor
However, human languages are not that strictly defined, so you can probably use it always, you just need to have good arguments for your usage. A good arguable case:
function Animal(name){//actually rather a factory function
return {name};
}
var cat = new Animal("bob");//and now ? :/
So, can any function object be called constructor?
But not every function creates or initializes objects. Consider this example:
function add(a, b) {
return a + b;
}
This function only adds two values.
What is constructor? What kind of function object can be called constructor?
I'd argue that only functions that are intended to be called with new are supposed to be considered "constructors" (that includes functions created via class).
However, you can also create objects without calling a function with new:
function getPerson(name) {
return {name: name};
}
Whether or not you consider such functions constructors is probably subjective.
This question already has answers here:
Is it ok to assign the JavaScript prototype object instead of just its properties?
(4 answers)
Closed 6 years ago.
In the following code a constructor function, an object instance, and two examples of changing a functions prototype. What is the difference between these two methods? As far as I can work out the second method will update the object instance even if it is after the declaration of that instance, whereas the other will not. Is this the only difference?
function Foo(name, color) {
this.name = name;
this.color = color;
}
var bar = new Foo('name', 'color');
First method:
Foo.prototype = {age: 6};
Second method:
Foo.prototype.age = 4;`
Foo.prototype = {age: 6};
First method is going to override constructor and ____proto____ link ,if you were using inheritance not a good approach becuase you will destroy the proto links and prototype chain
Its better to use
Foo.prototype.age = 4;`
In this way you are just only adding a property all the prototype chains will remail intact
This question already has answers here:
Javascript when to use prototypes
(6 answers)
Closed 7 years ago.
What is the difference between making a method using prototype and just creating it inside a function? E.g., what's the difference between methodOne and methodTwo below?
function myFunc() {
this.methodOne = function () { console.log("First method.")};
}
myFunc.prototype.methodTwo = function () { console.log("Second method.")};
They seem to behave the same way:
var myFuncInstance = new myFunc();
myFuncInstance.methodOne();
myFuncInstance.methodTwo();
But my sense is that methodTwo, by accessing the prototype directly, is doing something a little different.
The difference is that every instance of myFunc shares the same single instance of methodTwo, but has its own instance of methodOne.
I.e.
var foo = new myFunc();
var bar = new myFunc();
foo.methodOne === bar.methodOne; // false
foo.methodTwo === bar.methodTwo; // true
Taking this a bit further, if you are creating 1000 myFunc instances, you are creating 1000 methodOne functions that all do the same thing. There still would be only one methodTwo function.
With using the .prototype syntax you can add methods to existing objects. For example you can add a sum method to the array type using
Array.prototype.sum = function() {...}
Then use it as
var a = [1,2,3] and then doing a.sum()
With .prototype you can just keep on extending based on your needs just as you would in a class based language.