JS creating object in object with constructor - javascript

i have problem with assigning property to a object created with constructor INSIDE other function
var something = {
property1: 'sth',
object: new Object()
}
and it works it creates object inside a object, but everytime i try to assign property to object inside object like
var something = {
property1: 'sth',
object: new Object(),
object.property: 'anything'
}
it shows error, Uncaught syntaxError: unexpected token . , albo tried with object['property'] but shows "unexpected token [", so how do i assign it ?

You can do it in two steps:
var something = {
property1: 'sth',
object: new Object(),
};
something.object.property = 'anything';
Or use Object.assign to merge properties into the created object:
var something = {
property1: 'sth',
object: Object.assign(new Object(), {
property: 'anything',
}),
};
Of course if you are the one creating the object (as opposed to some third party function creating the object), there is no need to use new Object. Just use an object literal as well.

Related

spread in object definition causing undefined properties in "this"

I have an object which I initialize with bunch of properties in node.js, spreading another object in, and at the end defining a getter.
The problem is the the getter uses this and all the properties defined on the object before the spread don't exist on this.
If I move the spread to the end or start of the object initialization, it works fine.
const obj = { a: 1 }
const obj2 = {
prop: 'a',
...obj,
prop2: 'b',
get test() {
return this.prop + this.prop2
}
}
console.log(obj2.test); // 'undefinedb'
What can possibly be the reason for that?
Thanks

JavaScript access unknown properties of object

Situation:
I have multiple JS-Objects with the same structure.
In all of those Objects there's a property called console.
I'd like to assign a value (the same value) to each of these properties.
Please find below the structure of my code:
NameOfMyObject = function() {
return {
actions: null,
console: null,
init: function() {},
//object specific functions
}
};
My Problem:
Currently I'm assigning the value manual, but I want do do it generic.
Code snippet
this.console = console;
this.actions.console = console;
this.fixtures.console = console;
How can I access the properties of my objects?
I hope I asked my question clear enough.
Here is how you would share a property across objects:
function MyClass() {};
MyClass.prototype.console = {}; // Define a "common" property on the prototype
var obj1 = new MyClass(); // Create two instances
var obj2 = new MyClass();
Object.getPrototypeOf(obj1).console.id = 13; // Assign a value once...
console.log(obj1.console.id); // ... and it exists on both instances
console.log(obj2.console.id);
The shared property is on the prototype object.
Instead of Object.getPrototypeOf(obj1) you can of course use MyClass.prototype, since you know that obj1 was created by MyClass. They give the same prototype object.
If your property always has an object as value and you don't need to replace that value, only mutate it by setting properties on that object, then you don't need to explicitly reference the prototype to set a new value.
So this works:
function MyClass() {};
MyClass.prototype.console = {}; // Define a "common" property on the prototype
var obj1 = new MyClass(); // Create two instances
var obj2 = new MyClass();
obj1.console.id = 13; // Assign a value once... (getting console from the prototype)
console.log(obj1.console.id); // ... and it exists on both instances
console.log(obj2.console.id);
But if you change console itself, you'll be setting it on the instance, not on the prototype:
function MyClass() {};
MyClass.prototype.console = {}; // Define a "common" property on the prototype
var obj1 = new MyClass(); // Create two instances
var obj2 = new MyClass();
obj1.console = { id: 13}; // Setting an instance property now
console.log(obj1.console.id); // ... and it does not exist on both instances
console.log(obj2.console.id); // == undefined
So if that kind of assignment should still work on the prototype, you need to use the first code block with Object.getPrototypeOf or MyClass.prototype.

setting values to __proto__` and `prototype in javascript [duplicate]

This question already has answers here:
__proto__ VS. prototype in JavaScript
(34 answers)
Closed 6 years ago.
What is the difference between __proto__ and prototype
I read most of articles in the web and I still cannot understand it..
as far as I understand
__proto__ is the property which is for prototype object
prototype is the actual object
am I correct? ....
Why only functions have prototype property?
And how is it be an object?
var fn = function(){};
console.dir(fn);
output
function fn()
arguments: null
caller: null
length: 0
name: ""
prototype: Object
__proto__: ()
<function scope>
Using object and function I try to set values for __proto__
and prototype in chrome console as shown below
//create object and display it
var o = {name : 'ss'};
console.dir(o);
output
Object
name: "ss",
__proto__: Object
//set the values
o.__proto__ = 'aaa';
o.prototype = 'bbb';
//after set the values display the object
console.dir(o);
output
Object
name: "ss",
prototype: "aaa",
__proto__: Object
//create function and display it
var fn = function(){};
console.dir(fn);
output
function fn()
arguments: null
caller: null
length: 0
name: ""
prototype: Object
__proto__: ()
<function scope>
//set the values
fn.prototype = 'fff';
fn.__proto__ = 'eee';
//after set the values display the object
console.dir(fn);
output
function fn()
arguments: null
caller: null
length: 0
name: ""
prototype: "fff"
__proto__: function()
<function scope>
Then I realize that I can't set values for __proto__ but can set values to prototype . W why can't I set values for __proto__ ???
That's pretty simple actually.
{object}.__proto__ is a reference to {constructor function}.prototype object.
operator new {constructor function} (params) in JavaScript does three major things:
Creates new object, let it be 'obj'.
Calls that {constructor function} with this set to that newborn object (obj).
Sets obj.__proto__ = {constructor function}.prototype;
And that's pretty much it.
That obj.__proto__ establishes single linked list used to lookup for properties not defined in the object itself. As it is set to {constructor function}.prototype object then we can treat that prototype as a "rack" for object methods - functions associated with object instances.
Example:
function Foo() {}
Foo.prototype.bar = function() { return "foo.bar here"; }
var obj = new Foo(); // creating object with __proto__ set to Foo.prototype;
obj.bar(); // will return "foo.bar here"
In most languages, there are classes and objects. Classes inherit from other classes.
In JavaScript,
The inheritance is prototype-based. That means that there are no classes. Instead, an object inherits from another object.
Inheritance, the __proto__
When an object rabbit inherits from another object animal, in JavaScript that means that there is a special property set rabbit.__proto__ = animal.
When a rabbit's property is accessed, and the interpreter can’t find it in rabbit, it follows the __proto__ link and searches in animal.
var animal = { eats: true }
var rabbit = { jumps: true }
rabbit.__proto__ = animal // inherit
alert(rabbit.eats) // => true
The prototype property
When calling the constructor function, new operator implicitly sets the __proto__ property of the newly created object to the value of the constructor's prototype property.
var animal = { eats: true }
function Rabbit(name) {
this.name = name
}
Rabbit.prototype = animal
var rabbit = new Rabbit('John')
alert( rabbit.eats ) // => true
Complete Reference.

object issues of javascript

I constructed a function defined as
var Func1 = function()
{
return {
alert: function() { alert( "Lady Gaga" ); }
};
};
And I assigned Func1() to a variable, like this:
var func1 = Func1();
I found something make no sense to me that Func1() created an object for func1 although I didn't put the new in front of it.
Isn't that objects could only be created by new?
What happened when the expression above is being executed?
JavaScript doesn't need the new keyword. The above code assigned the return value to the newly created func1 variable.
When you write a javascript literal object (json like), it's the equivalent to create a new object with the new operator and assign its properties.
This
var a = { test: 123, caca: 'pipi' };
Is the same as
var a = new Object();
a.test = 123;
a.caca = 'pipi';
Look at what you are returning from Func1:
return {
alert: function() { alert( "Lady Gaga" ); }
};
You return an object, and that object is assigned to func1. So func1 = Func1(); simply calls Func1, and assigns the result of that to func1.
Your function is creating an object with:
{
alert: function() { alert( "Lady Gaga" ); }
};
Using that notation, there's no need to use the new operator.
The () actually executes the function, which returns an object with a method (a method is a property of type function).
In JS, you don't explicitly call new to create new objects:
var song = {
name: "Entrenched",
artist: "Morbid Angel"
};
song.artist = "Bolt Thrower";
This creates an object with the properties name and artist.
The new keyword used with a function is one way to create an object, but not the only way. It means that a new object will be created with the specified function called as a constructor - within the constructor the this keyword will reference the new object, and the new object will be returned. Call the same function without the new keyword and an object will not be created.
The object literal syntax (e.g., var x = { }; or return { };) is another way to create an object.

Overwrite Object function didn't affect {} expression?

I overwrite the Object constructor:
function Object() {
console.log("here");
}
when I call var x = new Object();, I can see "here".
However, when I call var x = {};, I can't got it.
Isn't {} the same as new Object()? How can I get this work?
using object() creates new function with name object with scope on document object, actually does not override object. While using var x = {}, it use original JS object.

Categories

Resources