how object.constructor() works? [duplicate] - javascript

This question already has answers here:
Javascript constructor return values [duplicate]
(2 answers)
Closed 5 years ago.
Recently I have attended one interview, Interviewer asked one interesting question have a look
function MyClass(){
this.a = 10;
return 20; // Interesting part
}
var obj1 = new MyClass();
console.log(obj1.a); // 10 works as expected.
console.log(obj1.constructor()); // 20 later I found this
how will you access return value(20) from obj1?
I found the answer after looking proto of the obj1.
obj1.constructor() Works as expected
Please help me to understand this.

See mdn:
The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn't explicitly return an object, the object created in step 1 is used instead. (Normally constructors don't return a value, but they can choose to do so if they want to override the normal object creation process.)
The 20 goes nowhere and cannot be accessed. It isn't an object, so the instance of MyCass is returned instead.

Related

why does `this` point to object [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 3 years ago.
In the following code, why test function's second this points to obj, whereas the first this points to window object?
In particular, how can I guess the value of this by looking at a piece of code?
var test = function(){
console.log('first', this)
return function(){
console.log('second', this)
}
}
var obj = {
a: 1,
b: test()
}
obj.b() // execute function
You call test on object creation triggering the first logging and store the created function to the object. You call that function on global level and therefore this gets resolved at that scope.
Is this some sort of interview question?
What are you trying to achieve/understand?
Edit:
See this guide for a good explanation of 'this':
https://dmitripavlutin.com/gentle-explanation-of-this-in-javascript/

Why do I need to bind a shadowed function that is called through the same object? [duplicate]

This question already has answers here:
How does the "this" keyword in Javascript act within an object literal? [duplicate]
(4 answers)
Closed 4 years ago.
Was doing some dirty things to Array.prototype when I ran into this:
Array.prototype.hook_pop = function(callback) {
var base_pop = this.pop.bind(this); //<-- this works
var base_pop = this.pop; //<-- this doesn't work
this.pop = function() {
var ret = base_pop();
callback(ret, this);
return ret;
}
}
Initially I tried using the non-working option and got an error "Uncaught TypeError: Cannot convert undefined or null to object".
The way I've understood it, unless otherwise bound, "this" should point to the object through which the method is called from, in this case the array instance. When called on the same object though, either way, "this" should be the same when being passed to the pop function, whether its bound or not. Why doesn't the second option work?
var ret = base_pop();
In this line you're invoking base_pop() by itself, and not as a method of any object. Because of this, its this value isn't set.

Javascript Functions and Objects Confusion [duplicate]

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 {};
}

Why does `this` refers to `o` here (o.method)() instead of a global object [duplicate]

This question already has answers here:
How does the "this" keyword work, and when should it be used?
(22 answers)
Closed 6 years ago.
Suppose I have an object:
var o = {
prop: 3,
method: function() {return this.prop}
}
I was expecting this
(o.method)()
to return undefined, however it returned 3 meaning that this is set to o inside method. Why is it so? If you evaluate (o.method) separately, it evaluates to a standalone function, so I expected this to reference global object. Why, for example, the difference exists here:
(o.method)() vs (o.method || true)()
I know that o.method() will use o as context, the question is specifically about accessing the function first like this (o.method) and then calling it.
That's just how JavaScript's rules work. Unless you do some contortions, this usually means the thing before the . when you access the method prior to calling it. In this case, that's o.
The following statements are identical:
(o.method)();
o.method();
o.method.call(o);
o["method"]();
However, if you put the method on something else, it'll take on the meaning of the thing it's on:
var p = {prop: 42, method: o.method};
p.method(); // returns 42
var method = o.method;
var prop = 13;
method(); // returns 13
Note: As JavaScript grew to be much more than it was originally designed for, people realized that this probably wasn't the most intuitive way for this to work, so in ES6 if you use "Arrow Functions" (aka Lambda Functions) it won't rebind this.

this.method vs prototype.method - what is the difference [duplicate]

This question already has an answer here:
this.method = function(){} VS obj.prototype.method = function (){}
(1 answer)
Closed 9 years ago.
As in the topic, when we are defining a future object (for ex.):
function Person(name) {
this.sayName = function() {
console.log(this.name);
};
}
Person.prototype.sayName = function() {
console.log(this.name);
};
both methods will be available for newly created object. The only difference is that the 'this' expression will create this method for every instance and with 'prototype' it will be shared in memory (as far as I know). I've faced both expressions and what is interesting the first one is far more popular than the second one.
My question is... what is the proper way in JavaScript the first or the second ? ( I know both works but... what is the code engineering standard and why ).
The proper way is the second one (what else would you need prototypes for?).
The advantage of the first approach is ability to get something like private variables: if you declare a local variable in constructor (function Person), then you'll be able to use it in sayName method because of closures. And that variable will not be accessible out of your "class".

Categories