JavaScript puzzling output [duplicate] - javascript

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 ??

Related

Differentiate between object property call and get [duplicate]

This question already has answers here:
Add a return type of string when a function is accessed like a variable
(2 answers)
Passing Argument to JavaScript Object Getter
(3 answers)
JavaScript - Variable/object as string and function at the same time
(1 answer)
Closed 23 days ago.
Assume we have the following object
const foo = {
bar: "hello "
}
Is it possible to achieve the following result:
console.log(foo.bar) // logs "hello "
console.log(foo.bar("world")) // logs "hello world"
I want to be able to get or call the same property and apply a function if called
I have tried using Proxy https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy with apply() handler, however I was not able to find a working solution, every attempt ends at This expression is not callable. Type 'String' has no call signatures.

Attach a function stored as a variable to prototype while preserving value of `this` to point to instance [duplicate]

This question already has answers here:
Methods in ES6 objects: using arrow functions
(6 answers)
Are 'Arrow Functions' and 'Functions' equivalent / interchangeable?
(4 answers)
Closed 22 days ago.
I am trying to do the following:
Create a constructor function
Create a function and store it as a variable (the function will rely on value of this)
Attach the function to the prototype of the constructor function
I can't figure out how to keep value of this inside the function to be pointing to the instance.
This code is from ChatGPT and explains exactly what I want to do:
let myFunction = () => {
console.log(this.value);
};
function MyObject(value) {
this.value = value;
}
MyObject.prototype.showValue = myFunction;
BUT I either don't know how to use it or it straight up doesn't work as it suppose to.
The test I ran:
a = new MyObject('a')
b = new MyObject('b')
a.showValue() // I am expecting `a` to be printed out, but undefined is printed
b.showValue() // I am expecting `b` to be printed out, but undefined is printed
So what's happening here? Why is this not pointing to the instance? How do I go about fixing this?

Why are methods not valid constructors? [duplicate]

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.

What is this notation in JS, can someone please explain [duplicate]

This question already has answers here:
Javascript object literal: what exactly is {a, b, c}?
(3 answers)
Closed 4 years ago.
I came across this function, called generateMessage which takes 2 parameters and returns and object. The function is as follows:
var generateMessage = (from, text)=>{
return {
from,
text,
createdAt: new Date().getTime()
}
};
module.exports = {generateMessage};
This does NOT throw any errors, and attaches 3 properties to the returned object: '.from' , '.text' and '.createdAt', I am confused about the '.from' and '.text' properties.
My question is why don't we write from: from , text:text, in this way the returned object will have a proto property of .from and .text, which will have their values as the from and text from the parameters.
Why does just writing from and text for the returned object work in this case?
That's ECMAScript's 'shorthand''s property and notation:
http://es6-features.org/#PropertyShorthand
http://es6-features.org/#ObjectMatchingShorthandNotation
It's as the name suggests, a shorthand method of object definition.

Do Javascript variable assignments work by reference? [duplicate]

This question already has answers here:
JavaScript by reference vs. by value [duplicate]
(4 answers)
Closed 8 years ago.
I have a question about referencing objects in javascript.
Say I have a variable that is some object (lets say json) and it is called objOne - (var objOne = someJSONObject;).
If I go ahead and declare
var objTwo = objOne;
will I have two references to the same Object? Kind of like a c pointer?
To sum it up :
assignements are done by value
you never manipulate objects, only object references
This means that
you'll have two references to the same object (you can check that by changing a property of the object)
when you're passed in a variable the value of a primitive, changing your variable doesn't change other variables
EDIT : as it's a duplicate I'll delete this answer in a minute to allow a proper closing if there's no other answer. Please vote to close.
Yes, objects are passed by reference:
function changeVal(obj){
obj.value = "bar"
}
(function checkRefs(){
var myObject = {
value: "foo"
};
alert(myObject.value);
changeVal(myObject);
alert(myObject.value);
})();

Categories

Resources