Is it possible to have a self executing function which is an objects property value assign values to other properties in the object?
e.g. - what I would like to do is this:
var b={
c:'hi',
d:null,
e:new function(){this.d=5}
};
But the "this" inside the new function seems to refer to b.e. Is it possible to access the b.e parent (i.e. b) from inside the function?
Methods—setting functions as properties of objects. In JavaScript, you can use functions as values, just like numbers, strings, and objects. That means you can pass them as arguments, return them from other functions, and set them as properties of objects.
A JavaScript function that runs as soon as it is defined. Also known as an IIFE (Immediately Invoked Function Expression).
An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.
Object.assign() Method Among the Object constructor methods, there is a method Object. assign() which is used to copy the values and properties from one or more source objects to a target object. It invokes getters and setters since it uses both [[Get]] on the source and [[Set]] on the target.
This is how you do it.
Often called the module pattern (more info)
var b = function () {
var c = 'hi';
var d = null;
return {
c : c,
d : d,
e : function () {
// this function can access the var d in the closure.
d = 5;
}
}
}();
You can access the value within the function
, you just need to get rid of the new
, i.e.
e: function () {
this.d = 5;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With