JS - Defining prototype methods [duplicate] - javascript

This question already has answers here:
Defining a Javascript prototype
(5 answers)
Closed 5 years ago.
Is there a difference between this syntax
function Foo() {}
Foo.prototype.method1 = function() {};
Foo.prototype.method2 = function() {};
and this one?
function Foo() {}
Foo.prototype = {
method1: function() {},
method2: function() {}
}
Should one be prefered to the other?

There is a slight difference between those two options. I would recommend using the former to preserve the constructor property pointing to the actual constructor function used to create the object. In the following example you'll see the difference under the hood of both options:
Foo used the prototype.newMethod syntax.
Bar used the prototype = {...} syntax.
In case you'd like to use the Bar syntax, you can always set the constructor property to the correct function.
I hope this helps, let me know if you have any doubts.

Related

Javascript Constructor vs Object Literal Confusion [duplicate]

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 ()

Inconsistent scope of 'this' in javascript [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 7 years ago.
In javascript all functions are objects. So how come when I use 'this' like so:
var myObj = function() {
doSomething: function() {
alert('msg');
}
myFunc2: function () {
this.doSomething(); //'this' doesn't equal myFunc2, it's myObj
}
}
'this' refers to myObj and not myFunc2? Javascript has function scope, 'this' is being used in myFunc2 so it should refer to myFunc2.
Why is this not the case? This language seems very inconsistent at times.
JavaScript doesn't have "function scope", what you are experimenting the how the this works in JavaScript.
The this keyword always reference the object that is calling the function, in this case, myObj.
Check this chapter from the You Don't Know JS book series to learn more about how this works in JavaScript:
You Don't Know JS: this & Object Prototypes

Javascript prototypes methods vs. internal methods [duplicate]

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.

Why people follow different approach to define function in javascript [duplicate]

This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed 8 years ago.
few years back people always define function like this way
1) function foo() {}
now i have noticed people define function like this way
2) var foo= function () {}
3) foo: function() {}
4) var GaugeBar = GaugeBar || {};
GaugeBar.generate = function (percentage) {}
so anyone JavaScript expert would tell me why people follow different approach for defining function? each signature has any special significance ?
when we should follow which one?
looking for good explanation. thanks
I think that there is some confusion in your question - the only valid approach to define a function is 1) and 2). The other two are just different uses of functions in objects.
I personally like to define named functions (function myFunc () {}) because if my program crashes the function names will appear in stack traces. However, there are situations where I use anonymous functions if those functions are not part of a public API or if they are used only once in my program.
Option 3) is basically a function that gets assigned to an object:
var myObject =
{ func: function () {}
, func2: function () {}
}
Option 4) is merely a way how to ensure that a variable contains an object and after that adding some functions to that object.
In practical terms, there is no difference whether you give your functions a name or you use anonymous functions (except for the stack traces and for differences already described in this SO question) and I believe it depends on the programmer's preferred code style. I would love if everyone named their publicly accessible functions as it makes debugging easier, but that's up to each developer to decide.

JavaScript Function Declaration vs Object Literal [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript object creation using literals vs custom constructor functions
Function vs. Object Literal Notaion - Which is better, or is it a matter of preference?
Could anyone enlighten me what is the difference between below two ways of creating objects in JavaScript or more specifically drawbacks/advantages of them:
Function Foo() {
function bar () {...}
}
And
var Foo = {
bar : function() {}
}
Also since in latter way, there is no this keyword, how can I make it object instance member ?

Categories