This question already has answers here:
How do I correctly clone a JavaScript object?
(81 answers)
Closed 4 years ago.
Consider this example:
If you were to take the above code and run it, the console message would be 100. Why does it print out 100 when I added the 100 to the position in obj2's "this"? How do I make it so that obj2 has its own unique "this"? Also please know that is an simplified example of my code, I cannot just make a seperate object in obj2 which contains everything.
var obj1 = function() {
this.obj2Arr = [];
this.pos = {
"x": 0,
"y": 0
};
this.obj2Arr.push(new obj2(this.pos));
console.log(this.pos.x);
// Prints out 100 even though obj2 was where I added the 100 for it's "this".
// Why does it do that, and how do I make obj2's "this" unique to it?
};
var obj2 = function(pos) {
this.pos = pos;
this.pos.x = this.pos.x + 100;
};
var example = new obj1();
console.log(example);
This is because pos is an object and objects are always passed by reference in javascript.
To answer your question: use Object.assign to create a fresh object:
var obj1 = function() {
this.obj2Arr = [];
this.pos = {
"x": 0,
"y": 0
};
this.obj2Arr.push(new obj2(Object.assign({}, this.pos)));
console.log(this.pos.x);
};
var obj2 = function(pos) {
this.pos = pos;
this.pos.x = this.pos.x + 100;
};
var example = new obj1();
console.log(example);
Related
This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 5 years ago.
Basically the code says everything. I have a variable x with a css property. I'm saving all the css of x into y, and then I change the value of the y's property. This change also affects x, why? How to make it to only pass the value so that x stays unchanged?
var x = {};
x.css = {height: 100, width: 100};
var y = {};
y.css = x.css;
y.css.height = 200;
console.log(x.css.height); //equals to 200 while it should be 100
Javascript assignment is done by reference and hence your x.css is also modified when you modify y.css . You can rather assign y.css using Object.assign.
var x = {};
x.css = {height: 100, width: 100};
var y = {};
y.css = Object.assign({}, x.css);
y.css.height = 200;
console.log(x.css.height);
You're creating an object and then pointing two different variables at the same object. The most simplest explanation would be that you're are just giving variable x another name/variable accessor. Look at the below example to see how to overcome this, or you can create a copy of the object.
Solution 1: Use this trick to clone an object.
var x = {};
x.css = {height: 100, width: 100};
var y = JSON.parse(JSON.stringify(x));
y.css.height = 200;
console.log('Y Height:', y.css.height);
console.log('X Height:', x.css.height);
Solution 2: Create a new instance that has it's own local properties
var elementInstance = function() {
return {
css: {
height: 100,
width: 100
}
}
}
var x = new elementInstance();
var y = new elementInstance();
y.css.height = 200;
console.log(x, y); // They should be different instances
Here's part of my code:
class Light {
constructor(xpos,zpos,ypos,range,diffuser,diffuseg,digguseb,intensity,angle,exponent) {
this.xpos = xpos;
this.ypos = ypos;
this.zpos = zpos;
this.range = range;
this.diffuser = diffuser;
this.diffuseg = diffuseg;
this.diffuseb = diffuseb;
this.intensity = intensity;
this.angle = angle;
this.exponent;
[...]
Is there any way to move all given argument variables to this so I can access them later?
var lt = new Light(0,12,15,...);
alert(lt.zpos); //outputs '12'
I'm looking for a solution to put those 11 this lines to one
This does what you desire. The portion in mapArgsToThis which gets the argument names was taken from here. mapArgsToThis would be a helper function you would use when you want to be lazy.
var mapArgsToThis = function(func, args, thisPointer) {
var argsStr = func.toString().match(/function\s.*?\(([^)]*)\)/)[1];
var argNames = argsStr.split(',').map(function(arg) {
return arg.replace(/\/\*.*\*\//, '').trim();
}).filter(function(arg) {
return arg;
});
var argValues = Array.prototype.slice.call(args);
argNames.forEach(function(argName, index) {
thisPointer[argName] = argValues[index];
});
};
var MyConstructor = function(xpos,zpos,ypos,range,diffuser,diffuseg,digguseb,intensity,angle,exponent) {
mapArgsToThis(MyConstructor, arguments, this);
};
var myInstance = new MyConstructor(1,2,3,4,5,6,7,8,9,0);
console.log(myInstance);
Even though this is a solution, I don't recommend it. Typing out the argument mapping to your this properties is good for your fingers and is easier for others to read and know what's going on. It also doesn't allow for any processing of the argument values prior to assignment onto this.
I am trying to learn how to work with javascripts prototype, I am only getting into it now. Please Excuse me if I ask ridiculously stupid questions
I just have a few pre-questions:
Is it worth learning? I mean it looks like a structured/clean
approach to me?
Do/should you use this with jQuery this?
is there any major problems or reason not to use it and why isn't it commonly used or am i just slow?
Actual Question:
I have the following code:
var BudgetSection = function BudgetSection(name ) {
this.id = "";
this.name = name;
this.monthlyTotal = 0.00;
this.yearlyTotal = 0.00;
this.subTotal = 0.00;
this.lineItems = [];
};
BudgetSection.prototype.calculateSubTotal = function() {
this.subTotal = ((12 * this.monthlyTotal) + this.yearlyTotal);
};
function BudgetLineItem(name) {
this.id = "";
this.name = name;
this.monthlyAmount = 0.00;
this.yearlyAmount = 0.00;
}
BudgetLineItem.prototype = {
totalAmount : function() {
var result = ((12 * this.monthlyAmount) + this.yearlyAmount);
return result;
}
};
var budgetSections = [];
section = new BudgetSection("test1");
section.lineItems.push(new BudgetLineItem('sub'));
section.lineItems.push(new BudgetLineItem('sub2'));
section.lineItems.push(new BudgetLineItem('sub3'));
budgetSections.push(section);
section = new BudgetSection("test2");
section.lineItems.push(new BudgetLineItem('sub'));
section.lineItems.push(new BudgetLineItem('sub2'));
section.lineItems.push(new BudgetLineItem('sub3'));
budgetSections.push(section);
section = new BudgetSection("test3");
section.lineItems.push(new BudgetLineItem('sub'));
section.lineItems.push(new BudgetLineItem('sub2'));
section.lineItems.push(new BudgetLineItem('sub3'));
budgetSections.push(section);
// first iterate through budgetSections
for ( var t = 0; t < budgetSections.length; t++) {
var sec = budgetSections[t];
console.log(sec);
// iterate through each section's lineItems
for (var q = 0; q< budgetSections[t].lineItems.length ; q++) {
var li = budgetSections[t].lineItems[q];
console.log(li);
}
}
the first BudgetSection "test1" is at index 0 in the budgetSections array. how can i assign the id to "section_".
And then also how can i set the id of BudgetLineItem like so: lineItemRow_<section_index><lineitem_index>
Also finally n the for loop what would be the best way to generate html?
I personally never use the new keyword if I can avoid it and do pure prototype-based programming with Object.create. Here's a simple example. I create a prototype-object called rectangle and then create an object called myRectangle which inherits from rectangle.
var rectangle = {
init: function( x, y, width, height ) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
},
move: function( x, y ) {
this.x += x;
this.y += y;
}
};
var myRectangle = Object.create( rectangle );
myRectangle.init( 0, 0, 2, 4 );
myRectangle.move( 3, 5 );
To explain in more depth what happens here, Object.create makes a new object with a specified prototype. When we access a property on an object (like init or move), it first checks the object itself. If it can't find it there, it moves up to the object's prototype and checks there. If it's not there, it checks the prototype's prototype, and keeps going up the prototype chain until it finds it.
When we call a function on an object (myRectangle.init()), this inside the function refers to that object, even if the function definition is actually on the prototype. This is called delegation - an object can delegate its responsibilities to its prototype.
A more class-like way to do this is:
function Rectangle( x, y, width, height ) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
Rectangle.prototype.move = function( x, y ) {
this.x +=x;
this.y +=y;
};
var myRectangle = new Rectangle( 0, 0, 2, 4 );
myRectangle.move( 3, 5 );
The problem is when we need to do a deeper inheritance hierarchy:
function Parent() {
/* expensive and possibly side-effect inducing initialization */
}
Parent.prototype.parentMethod = function() {};
function Child() {}
Child.prototype = new Parent();
We have to initialize a Parent object when all we really want is to set the Child prototype to an object based on Parent.prototype. Another option is:
Child.prototype = Object.create( Parent.prototype );
But now we've got this confusing, convoluted mess of prototype-based and class-based code. Personally, I like this instead:
var parent = {
parentMethod: function() {}
};
// Using underscore for stylistic reasons
var child = _.extend( Object.create( parent ), {
childMethod: function() {}
});
var instance = Object.create( child );
instance.parentMethod();
instance.childMethod();
No new keyword needed. No fake class system. "Objects inherit from objects. What could be more object-oriented than that?"
So what's the catch? Object.create is slow. If you're creating lots of objects, it's better to use new. You can still use Object.create to set up the prototype chain, but we'll have to wait a bit for browsers to optimize it enough for lots of instantiation.
Have you tried budgetSections[0].id = 'yourID';?
I'm inheriting an object from the EASELJS library.
To simplify the problem, I'm reducing the code into the minimal form.
I have a class:
this.TESTProg = this.TESTProg || {};
(function() {
var _jsbutton = function(x, y, text, icon) {
p.init(x, y, text, icon);
};
var p = _jsbutton.prototype = new createjs.Container();
p.x = 0;
p.y = 0;
p.text = null;
p.icon = null;
p.init = function(x, y, text, icon) {
this.x = 0 + x;
this.y = 0 + y;
this.text = "" + text;
this.icon = null;
};
TESTProg._jsbutton = _jsbutton;
})();
Then I use it in another js object:
var buttoncancel = new SJSGame._jsbutton(
profileselConfig.cancelx, //this is defined in another jsfile:
profileselConfig.cancely,
"cancel", "_cancel.png");
console.log( buttoncancel.y ); //this gives 240
var buttoncancel2 = new SJSGame._jsbutton(
profileselConfig.cancelx,
profileselConfig.cancely - 40,
"cancel", "_cancel.png");
console.log( buttoncancel.y ); //this gives 200
console.log( buttoncancel2.y ); //this gives 200
buttoncancel2.y = 100;
console.log( buttoncancel.y ); //this now gives 200 (not changed by the second object)
console.log( buttoncancel2.y ); //this now gives 100
The config file:
var _profileselConfig = function(){
this.cancelx = 0;
this.cancely = 240;
};
profileselConfig = new _profileselConfig();
And what am i doing wrong?
I'm already using 0 + to avoid passing the reference and it's not working. What should I do now? Any suggestions? Thanks.
You should probably be calling this.init rather than p.init in your constructor.
When you call p.init, the this inside of init refers to the prototype. Thus, whenever you create an instance, your p.init call modifies the prototype for all _jsbutton objects.
That's why both buttons have the same x/y values: they both get their position from the same prototype, and the last-run constructor set the prototype values. When you set buttoncancel2.y outside of the constructor, you gave that instance its own y property, so it no longer used the shared prototype value.
If you call this.init in your constructor, then the this in init will refer to your newly-created instance. The instances will no longer use the shared prototype values for x, y, text, and icon.
Side note: "I'm already using 0 + to avoid passing the reference" -- this is not necessary, because primitive types are always copied.
This question already has answers here:
Javascript: operator overloading
(9 answers)
Overloading Arithmetic Operators in JavaScript?
(11 answers)
Closed 7 years ago.
Is it possible to define custom operators between instances of a type in JavaScript?
For example, given that I have a custom vector class, is it possible to use
vect1 == vect2
to check for equality, whilst the underlying code would be something like this?
operator ==(a, b) {
return a.x == b.x && a.y == b.y && a.z == b.z;
}
(This is nonsense of course.)
I agree that the equal function on the vector prototype is the best solution. Note that you can also build other infix-like operators via chaining.
function Vector(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
Vector.prototype.add = function (v2) {
var v = new Vector(this.x + v2.x,
this.y + v2.y,
this.z + v2.z);
return v;
}
Vector.prototype.equal = function (v2) {
return this.x == v2.x && this.y == v2.y && this.z == v2.z;
}
You can see online sample here.
Update: Here's a more extensive sample of creating a Factory function that supports chaining.
No, JavaScript doesn’t support operator overloading. You will need to write a method that does this:
Vector.prototype.equalTo = function(other) {
if (!(other instanceof Vector)) return false;
return a.x == b.x && a.y == b.y && a.z == b.z;
}
Then you can use that method like:
vect1.equalTo(vect2)
The best you can do if you want to stick with the == operator:
function Vector(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
Vector.prototype.toString = function () {
return this.x + ";" + this.y + ";" + this.z;
};
var a = new Vector(1, 2, 3);
var b = new Vector(1, 2, 3);
var c = new Vector(4, 5, 6);
alert( String(a) == b ); // true
alert( String(a) == c ); // false
alert( a == b + "" ); // true again (no object wrapper but a bit more ugly)
No, it's not part of the spec (which doesn't mean that there aren't some hacks).
You can change built-in methods of objects in JavaScript, such as valueOf() method. For any two objects to apply the following operators >, <, <=, >=, -, + JavaScript takes the property valueOf() of each object, so it deals with operators kind of like this: obj1.valueOf() == obj2.valueOf() (this does behind the scenes). You can overwrite the valueOf() method depends on your needs. So for example:
var Person = function(age, name){
this.age = age;
this.name = name;
}
Person.prototype.valueOf(){
return this.age;
}
var p1 = new Person(20, "Bob"),
p2 = new Person(30, "Bony");
console.log(p1 > p2); //false
console.log(p1 < p2); //true
console.log(p2 - p1); //10
console.log(p2 + p1); //40
//for == you should the following
console.log(p2 >= p1 && p2 <= p1); // false
So this is not the precise answer for your question, but I think this can be an useful stuff for that kind of issues.
It isn't a direct answer for you question but it's worth to note.
PaperScript is a simple extension of JavaScript that adds support for operator overloading to any object.
It used for for making Vector graphics on top of HTML5 Canvas.
It parse PaperScript to JavaScript on script tag with type="text/paperscript":
<!DOCTYPE html>
<html>
<head>
<!-- Load the Paper.js library -->
<script type="text/javascript" src="js/paper.js"></script>
<!-- Define inlined PaperScript associate it with myCanvas -->
<script type="text/paperscript" canvas="myCanvas">
// Define a point to start with
var point1 = new Point(10, 20);
// Create a second point that is 4 times the first one.
// This is the same as creating a new point with x and y
// of point1 multiplied by 4:
var point2 = point1 * 4;
console.log(point2); // { x: 40, y: 80 }
// Now we calculate the difference between the two.
var point3 = point2 - point1;
console.log(point3); // { x: 30, y: 60 }
// Create yet another point, with a numeric value added to point3:
var point4 = point3 + 30;
console.log(point4); // { x: 60, y: 90 }
// How about a third of that?
var point5 = point4 / 3;
console.log(point5); // { x: 20, y: 30 }
// Multiplying two points with each other multiplies each
// coordinate seperately
var point6 = point5 * new Point(3, 2);
console.log(point6); // { x: 60, y: 60 }
var point7 = new Point(10, 20);
var point8 = point7 + { x: 100, y: 100 };
console.log(point8); // { x: 110, y: 120 }
// Adding size objects to points work too,
// forcing them to be converted to a point first
var point9 = point8 + new Size(50, 100);
console.log(point9); // { x: 160, y: 220 }
// And using the object notation for size works just as well:
var point10 = point9 + { width: 40, height: 80 };
console.log(point10); // { x: 200, y: 300 }
// How about adding a point in array notation instead?
var point5 = point10 + [100, 0];
console.log(point5); // { x: 300, y: 300 }
</script>
</head>
<body>
<canvas id="myCanvas" resize></canvas>
</body>
</html>
Here is a simple emulation which tests for equality using the guard operator:
function operator(node)
{
// Abstract the guard operator
var guard = " && ";
// Abstract the return statement
var action = "return ";
// return a function which compares two vector arguments
return Function("a,b", action + "a.x" + node + "b.x" + guard + "a.y" + node + "b.y" + guard + "a.z" + node + "a.z" );
}
//Pass equals to operator; pass vectors to returned Function
var foo = operator("==")({"x":1,"y":2,"z":3},{"x":1,"y":2,"z":3});
var bar = operator("==")({"x":1,"y":2,"z":3},{"x":4,"y":5,"z":6});
//Result
console.log(["foo",foo,"bar",bar]);
For non-strict mode functions the array index (defined in 15.4) named data properties of an arguments object whose numeric name values are less than the number of formal parameters of the corresponding function object initially share their values with the corresponding argument bindings in the function’s execution context. This means that changing the property changes the corresponding value of the argument binding and vice-versa. This correspondence is broken if such a property is deleted and then redefined or if the property is changed into an accessor property. For strict mode functions, the values of the arguments object‘s properties are simply a copy of the arguments passed to the function and there is no dynamic linkage between the property values and the formal parameter values.
References
The `arguments` object changes if parameters change
Annotated ES5: The Arguments Object
Javascript check arguments for zero value