Why are methods not valid constructors? [duplicate] - javascript

This question already has answers here:
Constructor behaving differently using ES6 shorthand notation
(3 answers)
TypeError: function is not a constructor (evaluating 'new self.f(1)')
(1 answer)
What is the difference between these object literals?
(1 answer)
Closed 5 months ago.
Regardless of intent, it's unclear to me why one is valid and other other is not. If someone could point to the relevant part of the language spec, that would be especially helpful.
class Foo {
bar() {}
}
Foo.prototype.baz = function() {};
const f = new Foo();
new f.baz(); // Valid
new f.bar(); // invalid, throws error

As pointed out in the comments on the original question, the spec defines it this way. A constructor must have the internal [[Construct]]s, and while ordinary function expressions do get this slot set, method definitions do not. This is described in MDN (as another commenter pointed out) as well.

Related

JavaScript puzzling output [duplicate]

This question already has answers here:
Object Using name of prototype function name instead of its property
(2 answers)
When I assign prototype to function I get undesired output
(4 answers)
Does Javascript writable descriptor prevent changes on instances?
(3 answers)
Closed 3 years ago.
Consider the code below. The d1 object so created, does not have name property but why ? However, if I remove the setting of prototype as function object, things works fine. please note that below code is deliberately written like that to test how JS reacts !
function Dog(name){
this.name = name;
}
// Notice that I am putting function object as prototype
Dog.prototype = function(){}
var d1 = new Dog("happy");
console.log(d1.name); //gives empty string
console.dir(d1); // `d1` does not have name property
console.log(d1 instanceof Dog);// returns true ??

Adding custom function to object prototype [duplicate]

This question already has answers here:
ES6 arrow functions not working on the prototype?
(4 answers)
Arrow Functions and This [duplicate]
(5 answers)
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 3 years ago.
I'd like to know how to add a custom function to the array object using prototype.
I called my function get. get takes an index and returns the element from the array with that index. It's pointless i know, but im using it for educational purposes.
So this is how it'd look like using it.
const a = ['1' , '2' , '3'];
a.get(2) -----> returns '3'
This is what i've tried.
Array.prototype.get = index => {
return this[index];
};
let a = ['1','2' ,'3'];
console.log(a.get(1));
This returns undefined to me.
By using arrow function you can't bind "this" so in the context of the prototype this equals to "window".
Try this:
Array.prototype.get = function(index){
return this[index];
};
I would strongly discourage you from extending/overwriting native JavaScript internals. There are many reasons it's a dangerous practice and it will definitely cost you a lot in future, which happened few years ago to one of the well-known JS frameworks, called Prototype:
In April 2010, blogger Juriy 'kangax' Zaytsev (of Prototype Core) described at length the problems that can follow from monkey patching new methods and properties into the objects defined by the W3C DOM.[5] These ideas echo thoughts published in March 2010 by Yahoo! developer Nicholas C. Zakas They have been summarized as follows:
Cross browser issues: host objects are not subject to rules, non-compliant IE DOM behavior, etc.
Chance of name collisions
Performance overhead
More info

Different ways of naming functions in javascript [duplicate]

This question already has answers here:
What is the difference between a function expression vs declaration in JavaScript? [duplicate]
(5 answers)
var functionName = function() {} vs function functionName() {}
(41 answers)
"new" operator before declaring function
(2 answers)
Closed 7 years ago.
I'm having a hard time understanding the difference between these two functions. Are they the same? It seems like in the first case, appleOne is the name of the object, and in the second case, appleTwo is the name of the function. However, I read that functions and objects are the same in Javascript, so I'm confused...
var appleOne = new function(color) {
this.color = color;
}
function appleTwo (color) {
this.color = color;
}
Reference: Code from http://www.phpied.com/3-ways-to-define-a-javascript-class/
The difference is that the object associated with the variable appleTwo is a function object, which the object associated with the variable appleOne is not a function: it is a "regular" object with the field color.
I wouldn't say that "functions and objects are the same" in JavaScript. What is true is that there are several kinds of objects in JavaScript:
regular objects
arrays
functions
regular expressions
In the first example, you used an anonymous function as a constructor, so the object you produced and assigned to appleOne is a "regular" object. The second example uses a function declaration to define a function.
If your question was not about the difference, but rather why the first case "works" (because it is not a very common pattern), there are several S.O. questions available with the answer.

why can't I assign a property value to a following property in an object declaration? [duplicate]

This question already has answers here:
Self-references in object literals / initializers
(30 answers)
Closed 8 years ago.
I'm learning Javascript and I've come across something I don't understand. This is the part of my object code:
var monster =
{
...
//is the animation starting?
hiding: true,
delayDuration: Math.floor(Math.random() * 60),
currentDelay: this.delayDuration,
...
};
If I console.log (delayDuration) I get a value, but if I console.log (currentDelay) it says 'undefined'.
I don't understand why currentDelay doesn't take the value of delayDuration.
Can someone please explain this?
edit: #Bergi why did you mark this as duplicate? I couldn't find my question answered somewhere else
edit2: yup, it's a duplicate. At least now I know the words for what I was asking.
At the point of object creation neither monster nor any of it's properties are defined. You can't use variable from the same object you're in the process of constructing.
Also, Javascript uses function scoping, which means that the value of this will either be the window object or will be scoped to the closest instance you're creating using new (or other instance creation techniques).

There is any different between new F and new F()? [duplicate]

This question already has answers here:
Can we omit parentheses when creating an object using the "new" operator?
(6 answers)
Closed 5 years ago.
Think about the silution
function F(){}; //This is a Constructor function
Who can tell me there is any different between
var myInstance = new F;
and
var myInstance = new F();
? The new keyword execute followed Function immediately anyway whatever that is following by partheses ?
There is no difference. From the Mozilla Docs:
new constructor[([arguments])]
The parentheses are in square brackets, that means they are optional.
There is no practical difference, omitting the paranthesis can be done if no arguments are passed to simplify the grammar.
Note that some validators such as JSLint will report a warning if you leave them out though, as it is considered more consistent to always use the same syntax for invoking constructor functions regardless of arguments.
This similar example would be very bad if you get into this lazy habit:
var one = myFunc;
var two = myFunc();
These are two different variables, one is a function reference and the other is the return value of the function.

Categories

Resources