Functions in javascript with function as property

Javascript — calling an external function as a property of an object

I have an array of objects, at this moment there is just one object inside. In this object i have a function that elaborate some properties of the same object. The function is processed outside the array, but the result is NaN, i dont know how pass correctly the values.. Example

let arrayObj = [ < number1: 1, number2: 2, sum: sum(this.number1 , this.number2) >] function sum(n1, n2)

No @ozgur, the issue is when the object’s this binding is assigned, and is unrelated to the sum function call.

5 Answers 5

If you want a fully usable object during object creation, then use a Function object.

let arrayObj = [new function()< this.number1 = 1; this.number2 = 2; this.sum = sum(this.number1 , this.number2) >] // minor edit to return the sum instead of returning the result of the console log function sum(n1, n2) < console.log(n1 + n2); return n1 + n2; >for (let i in arrayObj)

However, if you are in need of this function at a later time, and want it accessible for all of those objects, then stop using anonymous objects and create an actual class or prototype.

function Point(number1, number2) < this.number1 = number1; this.number2 = number2; >Point.prototype.sum = function() < return this.number1 + this.number2; >let arrayObj = [ new Point(1,2), new Point(3,4), new Point(15,30) ]; for (let i in arrayObj)
class Point < constructor(number1, number2)< this.number1 = number1; this.number2 = number2; >get sum() < return this.number1 + this.number2; >> let arrayObj = [ new Point(1,2), new Point(3,4), new Point(15,30) ]; for (let i in arrayObj)

In this case i cant add a similary obj, its doesnt work. let arrayObj = [new function()< . >, < this.number1 = 10; this.number2 = 20; this.sum = sum(this.number1 , this.number2) >] Well, maybe is not not correct my approach to the problem. I want to creato an external function to call in different obj and pass different parameters

@Fedoro — You would create a new function for each object you wish to have during creation. So in your example in your comment here, you would need a new function in both spaces. If you wish to have a value passed in, you can do so in the function call, although it gets a little different to setup. If you expand on your situation a little, I could show that as well.

@Fedoro — If you intend to have more structure to objects, then make sure the logic is in the right place. Adding the sum property to the object at a later time, as shown in Ori’s answer, is inefficient (prototypes and classes only have their logic stored once in the interpreter), and is also bad design (as your logic is now located at the point of calling instead of at the point of creating). Instead, use a class or prototype.

Читайте также:  Комментарий

You can add that property to the object when you are iterating over it.

const arrayObj = [< number1: 1, number2: 2, >]; function sum(n1, n2) < return n1 + n2; >for (let i in arrayObj)

There has a simple solution. you can put an instant function in your sum property and under that function, send the other required values of the object by converting them into variables. See below:

function sum(n1, n2) < return n1 + n2; >const arrayObj = [ < 'number1': 1, 'number2': 2, 'sum': function () < let num1 = this.number1, num2 = this.number2; return sum(num1, num2); >>]; console.log(arrayObj.sum()) 

I have nicely formatted the code. I hope, it will help others to understand the code easily. By the way, I am a new contributor to StackOverflow. Thanks for your support. one more thing, if you want to fetch the sum from this object. you should call like arrayObj.sum() because the sum is now a function.

You should definitely add this comment in the answer as it is very unlikely that someone will read comment section.

You don’t have to make a seperate function, you can also write the sum function in the object itself. Now when you access the sum field in your object, it will sum the two values and return it.

let arrayObj = [ < number1: 1, number2: 2, sum: function() < return this.number1 + this.number2; >>] console.log(arrayObj[0].sum()); 

This requires the function to be called though, and will not assign the value during object creation.

I have found another interesting solution (I don’t remember where I had found it.) for this problem. Using getter function of javascript the problem can solve easily.You can use this in your object directly to use the external function. If a property (key) of an object se the external function to get a value and it have to behave like normal «key:value» pair (not being a method/function), then the getter function is the best way to use to get the value. To know more about it please read it.

function sum(n1, n2) < return n1 + n2; >const arrayObj = < get sum() , number1: 1, number2: 2, number3: 4, get totalsum() //using the sum property (that used external function) in another property. >; console.log(arrayObj); console.log('the sum of '+arrayObj.number1+' & '+arrayObj.number2+' is: '+arrayObj.sum); console.log('the sum of '+arrayObj.sum+' & '+arrayObj.number3+' is: '+arrayObj.totalsum);

Источник

Functions in javascript with function as property

Last updated: Jan 8, 2023
Reading time · 2 min

banner

# Call a Function inside an Object in JavaScript

You can call a function inside an object by declaring the function as a property on the object and invoking it, e.g. obj.sum(2, 2) .

An object’s property can point to a function, just like it can point to a string, number or other values.

Copied!
const obj = sum(a, b) return a + b; >, >; console.log(obj.sum(10, 10)); // 👉️ 20 console.log(obj.sum(10, 20)); // 👉️ 30

We declared a sum property on an object. The property points to a function.

Copied!
const obj = sum(a, b) return a + b; >, >; console.log(typeof obj.sum); // 👉️ "function"
Copied!
const obj = sum(a, b) return a + b; >, >; // 👇️ using dot notation console.log(obj.sum(10, 10)); // 👉️ 20 // 👇️ using bracket notation console.log(obj['sum'](10, 10)); // 👉️ 20

We used a shorthand property to define the function in the object.

When reading older code, you might see the following more verbose and outdated approach.

Copied!
// 👇️ older syntax const obj = sum: function (a, b) return a + b; >, >; console.log(obj.sum(10, 10)); // 👉️ 20 console.log(obj.sum(10, 20)); // 👉️ 30

The first approach is more concise and easier to read.

# Using the this keyword to access the object’s properties

You can use the this keyword to access the object’s properties inside of the function.

Copied!
const obj = num: 100, sum(a, b) return a + b + this.num; >, >; console.log(obj.sum(1, 1)); // 👉️ 102

In this particular context, the this keyword refers to the object.

You could also add a function to the object after it has been declared.

Copied!
const obj = num: 100, >; obj.sum = function (a, b) return a + b + this.num; >; console.log(obj.sum(10, 10)); // 👉️ 120

Notice that we used the function keyword to define the function.

Had we used an arrow function, the value of the this keyword would not be correctly bound and would point to the enclosing scope (not the object).

Copied!
const obj = num: 100, >; obj.sum = (a, b) => console.log(this); // 👉️ undefined // ⛔️ error return a + b + this.num; >; console.log(obj.sum(10, 10));

Arrow functions don’t have their own this keyword like named functions do.

Instead, arrow functions use the this context of the enclosing scope.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Functions in javascript with function as property

Last updated: Jan 8, 2023
Reading time · 2 min

banner

# Call a Function inside an Object in JavaScript

You can call a function inside an object by declaring the function as a property on the object and invoking it, e.g. obj.sum(2, 2) .

An object’s property can point to a function, just like it can point to a string, number or other values.

Copied!
const obj = sum(a, b) return a + b; >, >; console.log(obj.sum(10, 10)); // 👉️ 20 console.log(obj.sum(10, 20)); // 👉️ 30

We declared a sum property on an object. The property points to a function.

Copied!
const obj = sum(a, b) return a + b; >, >; console.log(typeof obj.sum); // 👉️ "function"
Copied!
const obj = sum(a, b) return a + b; >, >; // 👇️ using dot notation console.log(obj.sum(10, 10)); // 👉️ 20 // 👇️ using bracket notation console.log(obj['sum'](10, 10)); // 👉️ 20

We used a shorthand property to define the function in the object.

When reading older code, you might see the following more verbose and outdated approach.

Copied!
// 👇️ older syntax const obj = sum: function (a, b) return a + b; >, >; console.log(obj.sum(10, 10)); // 👉️ 20 console.log(obj.sum(10, 20)); // 👉️ 30

The first approach is more concise and easier to read.

# Using the this keyword to access the object’s properties

You can use the this keyword to access the object’s properties inside of the function.

Copied!
const obj = num: 100, sum(a, b) return a + b + this.num; >, >; console.log(obj.sum(1, 1)); // 👉️ 102

In this particular context, the this keyword refers to the object.

You could also add a function to the object after it has been declared.

Copied!
const obj = num: 100, >; obj.sum = function (a, b) return a + b + this.num; >; console.log(obj.sum(10, 10)); // 👉️ 120

Notice that we used the function keyword to define the function.

Had we used an arrow function, the value of the this keyword would not be correctly bound and would point to the enclosing scope (not the object).

Copied!
const obj = num: 100, >; obj.sum = (a, b) => console.log(this); // 👉️ undefined // ⛔️ error return a + b + this.num; >; console.log(obj.sum(10, 10));

Arrow functions don’t have their own this keyword like named functions do.

Instead, arrow functions use the this context of the enclosing scope.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

attach get/set function to objects property in js

I need to trigger refresh anytime .setting is written to. I feel like it has something to do with bind , but I couldn’t quite get it.

6 Answers 6

You could use JavaScript getters and setters. See the MDC documentation on the subject and John Resig’s blog post on the subject. Note that not all browsers support this.

var Foo = function()//constructor < this._settings = false;//hidden variable by convention this.__defineGetter__("settings", function()< return _settings;//now foo.settings will give you the value in the hidden var >); this.__defineSetter__("settings", function(s)< _settings = s;//set the hidden var with foo.settings = x this.refresh();//trigger refresh when that happens >); this.refresh = function() < alert("Refreshed!");//for testing >> var a = new Foo();//create new object a.settings = true;//change the property //a.refresh() is triggered 

You need to use a getter and a setter for your object. One way is to use getter/setter functions directly:

var foo = function() < this.setting = false; this.getSetting = function() < return this.setting; >this.setSetting = function(val) < this.setting = val; this.refresh(); >this.refresh = function() > 

If you want to use foo.setting transparently as an attribute, there are language constructs for that, but unfortunately they are not interoperable across browsers. In somewhat of a throwback to 3 years ago, there’s one method supported by Mozilla, Safari, Chrome and Opera and another method for Internet Explorer. This is the standard method:

IE9 has something else, and I’m not sure if it even works for non-DOM objects.

Источник

Оцените статью