- Javascript: Calling a function in an object literal
- Javascript: Calling a function in an object literal
- Call a function from an object
- Javascript: Calling object methods within that object
- Javascript calling function on object
- # Call a Function inside an Object in JavaScript
- # Using the this keyword to access the object’s properties
- # Additional Resources
Javascript: Calling a function in an object literal
As well, if you have a very large and complex object, it is arguably easier to read all the root elements on each line without expanding all the objects and arrays found within that object recursively. A variation which I think should work is Similarly, how does it work for objects meant to be created with the operator?
Javascript: Calling a function in an object literal
I’m learning to program in Javascript and I’d like some help/clarification.
I declared an array that contains animal names. I defined a function that I use to split a string in two. Then I create an empty object literal and add an animal and corresponding breed. I’m trying to invoke the separateWords function in the object literal, but I need some clarification. Here’s my code:
var myPets = ["Bengal Bobcat", "Beagle"]; var separateWords = function (string) < return string.split(" "); >; var nameCollection = <>; nameCollection.cat = separateWords(myPets[0]); nameCollection.dog = myPets[1]; nameCollection.fish = null;
When I enter console.log(nameCollection) I get the following:
Object cat: Array[2] 0: "Bengal" 1: "Bobcat" length: 2
However, when I enter console.log( separateWords(myPets[0])), I see:
I don’t understand why the value of cat shows up as Array[2].
The console displays it as Array[2] as it would be (potentially) unreadable if it expanded it fully. One way to see everything is to stringify it using JSON.stringify which goes through each item in the object recursively and calls toString() on it:
var myPets = ["Bengal Bobcat", "Beagle"];var separateWords = function (string) < return string.split(" "); >;var nameCollection = <>; nameCollection.cat = separateWords(myPets[0]); nameCollection.dog = myPets[1]; nameCollection.fish = null;document.body.textContent = JSON.stringify(nameCollection);
You are assigning to cat the result of the separateWords() function call, passing myPets[0] as a parameter.
separateWords() returns an array and with the myPets[0] input it returns a new array with the «Bengal» and «Bobcat» values splitted by the whitespace.
The split() function is the one creating an array with the splitted values and this result is returned by your separateWords() function, which also is the value assigned to the cat object member.
Each browser implements its console like it wants.
So your browser decided to implement the behavior you describe.
If you don’t like it, propose a better idea to the developers of this browser. Or use another browser.
I am going to assume you are using Chrome Developer Tools or Firebug.
Developer tools condenses arrays and objects into easily readable lines you then inspect further with. What I mean is, you push the little arrow next each line in the console log to further inspect each object. I will use pictures to explain this.
Here I am assigning an array and then assigning an element in an object to that array as so:
As you can see when I log the object it show’s an Array[2] rather than expand the array. In this next picture I then expand the array to inspect it.
Why is this exactly? My first thought is ease of readability. If you have an app that is complex and you have numerous debugging console logs, you can see all the logs on single lines making it easier to hunt down specific logs. As well, if you have a very large and complex object, it is arguably easier to read all the root elements on each line without expanding all the objects and arrays found within that object recursively.
Javascript: Calling object methods within that object, 2 Answers. Sorted by: 44. Well, from your first example: var _obj = < property: value, method1: function () < // do stuff >, method2: function () < // use property var prop = this.property; // call method1 this.method1 (); >>; That’s what the this value is for. Now, what you cannot do is refer to a property of an «under …
Call a function from an object
How can I call a function from an object in JavaScript , like for example in jquery you call myDiv.html() to get the html of that div.
So what I want is this to work :
this is a simplified example, so please don’t say : just do $(‘#foo’).html() 🙂
jQuery.fn.extend( < bar: function() < return this.html(); >>); alert($('#foo').bar());
You mean how you call a function with an object in context ?
Or if you want to attach a method to an object permanently,
obj = ; obj.prototype.bar = function() ; obj.bar();
To add a getHtml function to a div element with the id foo you could do this:
$("#foo")[0].getHtml = function () < return this.innerHTML; >; alert($("#foo")[0].getHtml());
If this is not what you wanted, but rather extend jQuery, you should have a look at the post by Alex Barrett.
Javascript Function Objects, Javascript Function Objects Property. An array corresponding to the arguments passed to a function. Refers the currently executing function. Refers the number of arguments defined for a function. Specifies the function that creates an object. The number of arguments defined by the function.
Javascript: Calling object methods within that object
What is the best design pattern for achieving the following (which doesn’t work)?
var obj = (function() < // code defining private variables and methods var _obj = < property: value, method1: function() < // do stuff >, method2: function() < // use property var prop = _obj.property; // obviously doesn't work // call method1 obj.method1(); // "obj" not finished being defined yet! >>; // obviously now I could do. var prop = _obj.property; return _obj; >)(); // and I could now do. obj.method1();
A variation which I think should work is
var obj = (function() < var property = value, method1 = function() < // do stuff >, method2 = function() < // use property var prop = property; // call method1 method1(); >, _obj = < property: property, method1: method1, method2: method2 >; return _obj; >)();
Similarly, how does it work for objects meant to be created with the new operator? Within the constructor function itself you can write this.method() . But what if you want to keep the constructor small, only defining those things which will likely be customized upon creation, and then defining the rest in the prototype? (This seems to be the common pattern.) Can the properties / methods within the prototype interact in any way?
var MyObj = function(name) < this.name = name; >; var obj = new MyObj('Bob'); MyObj.prototype = < called_often: function() < // lots more code than just the following return document.getElementById('someID').value; >, global_default: 'value', // can be changed, so need to pull value when run does_stuff: function(value) < var str = global_default + value, // can't access global_default on its own input = MyObj.called_often(), // doesn't work; MyObj.prototype.called_often() DOES name = this.name; // 'this' used in the prototype doesn't work // even within a created object return name + input + str; >>;
I’m sure there’s better ways to achieve my result whenever I run into this problem. This code isn’t situation specific and just illustrates the general problem. So you won’t be able to give me an alternative for those specific situations I run into. But maybe you can help my overall thinking.
Well, from your first example:
var _obj = < property: value, method1: function() < // do stuff >, method2: function() < // use property var prop = this.property; // call method1 this.method1(); >>;
That’s what the this value is for.
Now, what you cannot do is refer to a property of an «under construction» object from elsewhere in the object literal syntax. (It’s hard to give an example because it’s just not syntactically possible.) In cases where you want to do that, you do need one or more separate assignment statements.
Guess what? You are making simple stuff complex. Pointy’s answer is good, but the prototype way is better for several reasons. That’s why I am describing (rather, making corrections in) the last method. Check this fiddle.
var MyObj = function(name) < this.name = name; >; MyObj.prototype = < called_often: function() < // lots more code than just the following return 'VALUE'; //document.getElementById('someID').value; >, global_default: 'value', // can be changed, so need to pull value when run does_stuff: function(value) < var str = this.global_default + value, // can't access global_default on its own input = this.called_often(), // doesn't work; MyObj.prototype.called_often() DOES name = this.name; // 'this' used in the prototype doesn't work // even within a created object return name + input + str; >>; var obj = new MyObj('Bob');
Call a JavaScript function name using a string?, 10 Answers. Sorted by: 87. Property accessors can be used to access any object’s properties or functions. If the function is in the global scope, you can get it using the window object: var myFunc = window [myFuncName]; This also works within the this scope: var myFunc = this [myFuncName]; Share.
Javascript calling function on object
Last updated: Jan 8, 2023
Reading time · 2 min
# 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.