Calling Objects as Functions JavaScript - javascript

In JavaScript, functions are objects, except that they can be called and executed, this is comparable to overloading the () operator of an object in other languages.
Can I apply this functionality to any object?
I know there isn't a property like [Symbol.call] or something comparable. If there is something comparable, I would greatly appreciate it if you could inform me of what it is.
If declaring objects and assigning properties to them is my only option that's okay, but I'd prefer if this could be done using a class, like C++ for example.
I could do something like this
function func(...) {
...
}
func.foo = x,
func.bar = y;
but it would be more preferable if I could do something more like
const func = {
[`()`]: function(...) {
...
},
foo: x,
bar: y
};

Can I apply this functionality to any object?“
No. As of ECMAScript 10th Edition (2019) this is not possible.
The ()-operator/expression construct can only be used on function objects.
This is because it uses the [[Call]] internal method. Section 7.3.12 Call indicates this is only defined for function objects and the specification makes no provision to add the [[Call]] internal method to other objects.
7.3.12 Call ( F, V [ , argumentsList ] )
The abstract operation Call is used to call the [[Call]] internal method of a function object. [..]
The specification is written in such a way that a future revision might add generalized support.
Anyway, as shown in the question, function objects can be mutated as a proxy: so carry on, flavoring as desired.

So it might help to give a more concrete example of what you want, but here's a few options that can pretty much replicate, and more, the things you have mentioned.
This is like your first example. I'm guessing this isn't what you actually want. Notice foo and bar are static.
const func = Object.assign( function(in){ console.log(in, func.foo, func.bar) }, { foo: x, bar: y } );
This one is probably closer to what you'd see in a class with () overloaded
const func = ( function(in){ console.log(in, this.foo, this.bar) } ).bind({ foo: x, bar: y });
Or something like this:
o = o => o['()'].bind(o)
const func = o({
"()": function(x){ console.log(x, this.foo, this.bar) },
foo: 1,
bar: 2
});
Takes the property value of '()', and binds this to the object. You also use Object.assign to copy the properties on to the function.
Other way of expression
const func = (x,y) => ({
foo: x, bar: y,
plusone: () => func(x+1,y+1)
showfoo() { return this.foo }
})

You could do stuff like this, for example from within an outer IIFE function, returning different types of object formatted data. The IIFE can be passed as a parameter to another function in a modular script file, where controller's return data can be reached with dot notation controllerAsParameter.dostuff or controllerAsParameter.getNumbers.percentage.
Is my interpretation correct, based on your last example, that you're after something like this?
const controller = (function() {
return {
doStuff: function() {
data.everything.forEach(function(foo) {
foo.calculateStuff(data.totals.bar);
});
},
getNumbers: function() {
return {
abc: data.abc,
totalDef: data.totals.def,
totalGhi: data.totals.ghi,
percentage: data.percentage
}
}
}
})();

Related

Binding "this" in JS object

I'm trying to "reverse-engineer" JS code of one of my favorite web game. I'm not beginner in web developing, but JS is not my strength (nor english, sorry), I'm more backend programmer.
The code is full of such "objects":
var Foo = {
prop: {...},
prop2: [...],
bar: function(val) {
this.prop.k = val;
Foo.doSomething();
},
doSomething: function() {
var my = Foo.prop;
...
return this.prop2;
},
};
...somehere on the page...
<input type="text" name="in" value="Pretty text" onclick="Foo.bar(this.value)" />
As far as I understand it, it's object Foo made from anonymous class, making it somewhat static. But I'm very confused by using this and Foo as object name. It seems to me randomly used, one or another. It's not related to properties or functions, both are used both ways. Even in the same method is used both. I think, that in this case are this and Foo the same. When I try to make such an objects and dump them in console, this and Foo returns the same.
Can anyone explain to me, where can be a difference, please? Or can it be just something lost in translation, because original code is minified?
Thanks.
var x = {
something: 'something',
log: function() {
return this.something
},
log2: function() {
return x.something
}
}
If you run the above code, you can see that the log() method and log2() method both return the same result. Which concludes that this and x refers to the same object in this scenario. Yours might be the same case if I'm not wrong.
Here are some cases when this and the name of the object are not referring the same object.
let Foo = {
prop: 'a',
log() {
console.log(
'this.prop is', this.prop, ', Foo.prop is', Foo.prop
);
}
},
Bar = {
prop: 'b',
mock: Foo.log
},
Baz = Object.create(Foo, {
prop: {
value: 'c'
}
});
Foo.log();
Bar.mock();
Baz.log();
// You can also bind the this reference when calling
Bar.mock.call(Baz);
Baz.log.apply(Bar);
In Baz case, the original Foo.prop preserves its value, since setting a property with the same name in an instance makes it an own property of that instance, the value of the property in the prototype is not overridden.
All of these scenarios help you to reuse already written code, hence reducing the code. Whether this was a goal in your favorite web game or not is not known, when reading the short examples only. With the given code, there's no difference.

Curried JavaScript - calling

I am admittedly a beginner with JavaScript, but I need to piece together someone else's code and I am having trouble understanding the following function and how to call it in node.
const invoke = method => object => object[method]
This obviously is a function that takes a method that returns another function that takes an object that then returns object[method], but what exactly is the purpose? How would one use this? Thank you.
the way i see it is as the const states, it invokes a function stored in an object ,
as you mentionned, this can be broken down to :
const invoke = (method) => {
return (object) => {
return object[method] ;
}
}
the goal of this i believe is that you can call it ( like you're telling a story ) expressively and concisely : invoke the function a from the functions object. ( functionnal-programming )
from this article about functional programming
Functional programming is declarative rather than imperative, and
application state flows through pure functions. Contrast with object
oriented programming, where application state is usually shared and
colocated with methods in objects.
but the term invoke got me thinking about Immediately invoked functions, so the usage of the const invoke can be :
getting function from the object ( without executing it ) not to have to instantiate the whole object and having the function in a variable and maybe manipulate it's prototype.
calling the function ( with parenthesis ).
getting a property from an object.
immediately invoke a function in an object.
const myFns = {
'a' : function(x){
console.log(x || 'something to log when no params passed');
},
'b': {
username : 'Doe'
}
}
const invoke = method => object => object[method]
let myFunction = invoke('a')(myFns);
myFunction('hello from myFunction'); // call it or modify myFunction.prototype ... etc.
invoke('a')(myFns)('hello'); // simply call it
let user = invoke('b')(myFns); // get a property
console.log(user.username);
(invoke('a')(myFns))(); // immidiatly invoke the function
probalby to avoid eval() :P
The name 'invoke' suggests it should really be written like this:
const invoke = method => object => object[method]()
The () is the invocation. It's very general, so hard to say exactly how it would be used, but here's a silly example.
class Dog {
speak () { console.log('woof') }
}
var dogs = [ new Dog(), new Dog(), new Dog() ];
dogs.forEach( invoke( 'speak' ) );
-> 'woof'
-> 'woof'
-> 'woof'
It's a pretty common pattern to let an array method like forEach do the second call of a higher-order function like this.

Function versus Object constructor

I'm not exactly sure how to ask this question, so I'll do it by example. Say I have this set up:
var x = function() {
console.log('YAY!');
};
x.test0 = 0;
x.test1 = 1;
x.test2 = "hello world";
that works as expected:
x(); // YAY!
x.test0 // 0
x.test2 // "hello world"
Now, I would like to know how to set this up starting with an object first. I tried adding the function using constructor, but that doesn't work.
var x = {
test0 : 0,
test1 : 1,
test2 : 'hello world',
constructor: function() {
console.log('YAY!');
}
}
x(); // object is not a function
x.test0 // 0
x.test2 // "hello world";
I've tried other crazy things, but nothing seems to work.
Any ideas? Or am I stuck doing it the first way?
As demonstrated by your first example, functions in JavaScript are objects and can have properties.
ECMAScript defines "internal properties" (and internal methods) for objects. These internal properties help define the state of an object, but not all of an object's internal properties are directly settable from code. We denote an internal property name with double square brackets, like [[Foo]].
When you call a function like foo(), you run the object's [[Call]] internal method. However, only function objects have a [[Call]] internal method. It is not possible to set or change a non-host object's [[Call]] method; it is set when the object is defined and there is no mechanism defined by ECMAScript to change it. ("Host" objects are objects supplied by the browser or other execution environment and can play by different rules. Unless you're writing a browser, you probably don't need to consider this exception.)
Thus, if you define a function
foo = function() { doStuff(); return 5; };
that function (which is assigned to the variable foo) has a permanent [[Call]] method (per the function-creation rules in section 13.2), which runs doStuff and returns 5.
If you have a non-function object
foo = { };
that object is lacking a [[Call]] property. There is no way to give it a [[Call]] property, because non-host objects can only set [[Call]] at definition-time. The logical internal property [[Call]] does not correspond to any object property accessible in actual code.
In sum, making a non-function object callable is not possible. If you want an object to be callable, define it initially as a function, as you do in your first example.
To put it simply you can't. Why? because the types of both the objects are different first a Function Object and second returns a standard object. So both inherits from different ancestors. The only possibility here is if you can cast object to a function and there's no such thing available n JavaScript natively. However you can use your own cast method.
function toFunction (obj, fnProp) {
var fn = function () {};
if (typeof obj[fnProp] !== 'function') return fn;
else {
fn = obj[fnProp];
for (prop in obj) {
fn[prop] = obj[prop];
}
}
return fn;
}
var z = toFunction(y, 'prototype'); // with your example
You can't just create an object and later run it as if it were a function.
You can do it the other way around, as in JavaScript a function is an object:
x.prop=1;
console.log(x.prop);
function x() {
return true;
}
Did not got exactly what you want, do you want something like object oriented? This may help
function x(){
this.test0 = 0;
this.test1 = 1;
this.test2 = 'hello word';
console.log('Wow!');
}
var y = new x(); // new object of x PRINTS WOW and set's default values
console.log(y.test0) // 0
console.log(y.test2) // "hello world";

Method vs Functions, and other questions

With respect to JS, what's the difference between the two? I know methods are associated with objects, but am confused what's the purpose of functions? How does the syntax of each of them differ?
Also, what's the difference between these 2 syntax'es:
var myFirstFunc = function(param) {
//Do something
};
and
function myFirstFunc(param) {
//Do something
};
Also, I saw somewhere that we need to do something like this before using a function:
obj.myFirstFunc = myFirstFunc;
obj.myFirstFunc("param");
Why is the first line required, and what does it do?
Sorry if these are basic questions, but I'm starting with JS and am confused.
EDIT: For the last bit of code, this is what I'm talking about:
// here we define our method using "this", before we even introduce bob
var setAge = function (newAge) {
this.age = newAge;
};
// now we make bob
var bob = new Object();
bob.age = 30;
// and down here we just use the method we already made
bob.setAge = setAge;
To answer your title question as to what is the difference between a 'function' and a 'method'.
It's semantics and has to do with what you are trying to express.
In JavaScript every function is an object. An object is a collection of key:value pairs. If a value is a primitive (number, string, boolean), or another object, the value is considered a property. If a value is a function, it is called a 'method'.
Within the scope of an object, a function is referred to as a method of that object. It is invoked from the object namespace MyObj.theMethod(). Since we said that a function is an object, a function within a function can be considered a method of that function.
You could say things like “I am going to use the save method of my object.” And "This save method accepts a function as a parameter.” But you generally wouldn't say that a function accepts a method as a parameter.
Btw, the book JavaScript Patterns by Stoyan Stefanov covers your questions in detail, and I highly recommend it if you really want to understand the language. Here's a quote from the book on this subject:
So it could happen that a function A, being an object, has properties and methods, one of which happens to be another function B. Then B can accept a function C as an argument and, when executed, can return another function D.
There is a slight difference -
Method : Method is a function when object is associated with it.
var obj = {
name : "John snow",
work : function someFun(paramA, paramB) {
// some code..
}
Function : When no object is associated with it , it comes to function.
function fun(param1, param2){
// some code...
}
Many answers are saying something along the lines that a method is what a function is called when it is defined on an object.
While this is often true in the way the word is used when people talk about JavaScript or object oriented programming in general (see here), it is worth noting that in ES6 the term method has taken on a very specific meaning (see section 14.3 Method Definitions of the specs).
Method Definitions
A method (in the strict sense) is a function that was defined through the concise method syntax in an object literal or as a class method in a class declaration / expression:
// In object literals:
const obj = {
method() {}
};
// In class declarations:
class MyClass {
method() {}
}
Method Specificities
This answer gives a good overview about the specificities of methods (in the strict sense), namely:
methods get assigned an internal [[HomeObject]] property which allows them to use super.
methods are not created with a prototype property and they don't have an internal [[Construct]] method which means that they cannot be called with new.
the name of a method does not become a binding in the method's scope.
Below are some examples illustrating how methods (in the strict sense) differ from functions defined on objects through function expressions:
Example 1
const obj = {
method() {
super.test; // All good!
},
ordinaryFunction: function ordinaryFunction() {
super.test; // SyntaxError: 'super' keyword unexpected here
}
};
Example 2
const obj = {
method() {},
ordinaryFunction: function ordinaryFunction() {}
};
console.log( obj.ordinaryFunction.hasOwnProperty( 'prototype' ) ); // true
console.log( obj.method.hasOwnProperty( 'prototype' ) ); // false
new obj.ordinaryFunction(); // All good !
new obj.method(); // TypeError: obj.method is not a constructor
Example 3
const obj = {
method() {
console.log( method );
},
ordinaryFunction: function ordinaryFunction() {
console.log( ordinaryFunction );
}
};
obj.ordinaryFunction() // All good!
obj.method() // ReferenceError: method is not defined
A method is a property of an object whose value is a function. Methods are called on objects in the following format: object.method().
//this is an object named developer
const developer = {
name: 'Andrew',
sayHello: function () {
console.log('Hi there!');
},
favoriteLanguage: function (language) {
console.log(`My favorite programming language is ${language}`);
}
};
// favoriteLanguage: and sayHello: and name: all of them are proprieties in the object named developer
now lets say you needed to call favoriteLanguage propriety witch is a function inside the object..
you call it this way
developer.favoriteLanguage('JavaScript');
// My favorite programming language is JavaScript'
so what we name this: developer.favoriteLanguage('JavaScript');
its not a function its not an object? what it is? its a method
Your first line, is creating an object that references a function. You would reference it like this:
myFirstFunc(param);
But you can pass it to another function since it will return the function like so:
function mySecondFunction(func_param){}
mySecondFunction(myFirstFunc);
The second line just creates a function called myFirstFunc which would be referenced like this:
myFirstFunc(param);
And is limited in scope depending on where it is declared, if it is declared outside of any other function it belongs to the global scope. However you can declare a function inside another function. The scope of that function is then limited to the function its declared inside of.
function functionOne(){
function functionTwo(){}; //only accessed via the functionOne scope!
}
Your final examples are creating instances of functions that are then referenced though an object parameter. So this:
function myFirstFunc(param){};
obj.myFirst = myFirstFunc(); //not right!
obj.myFirst = new myFirstFunc(); //right!
obj.myFirst('something here'); //now calling the function
Says that you have an object that references an instance of a function. The key here is that if the function changes the reference you stored in obj.myFirst will not be changed.
While #kevin is basically right there is only functions in JS you can create functions that are much more like methods then functions, take this for example:
function player(){
this.stats = {
health: 0,
mana: 0,
get : function(){
return this;
},
set : function( stats ){
this.health = stats.health;
this.mana = stats.mana;
}
}
You could then call player.stats.get() and it would return to you the value of heath, and mana. So I would consider get and set in this instance to be methods of the player.stats object.
A function executes a list of statements example:
function add() {
var a = 2;
var b = 3;
var c = a + b;
return c;
}
1) A method is a function that is applied to an object example:
var message = "Hello world!";
var x = message.toUpperCase(); // .toUpperCase() is a built in function
2) Creating a method using an object constructor. Once the method belongs to the object you can apply it to that object. example:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.name = function() {return this.firstName + " " + this.lastName;};
}
document.getElementById("demo").innerHTML = person.fullName(); // using the
method
Definition of a method: A method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object.
var myFirstFunc = function(param) {
//Do something
};
and
function myFirstFunc(param) {
//Do something
};
are (almost) identical. The second is (usually) just shorthand. However, as this jsfiddle (http://jsfiddle.net/cu2Sy/) shows, function myFirstFunc will cause the function to be defined as soon as the enclosing scope is entered, whereas myFirstFunc = function will only create it once execution reaches that line.
As for methods, they have a this argument, which is the current object, so:
var obj = {};
obj.func = function( ) {
// here, "this" is obj
this.test = 2;
}
console.log( obj.test ); // undefined
obj.func( );
console.log( obj.test ); // 2
The exact syntax you showed is because you can also do this:
function abc( ) {
this.test = 2;
}
var obj = {};
obj.func = abc;
obj.func( ); // sets obj.test to 2
but you shouldn't without good reason.
ecma document
4.3.31method :
function that is the value of a property
NOTE When a function is called as a method of an object, the object is
passed to the function as its this value.
It is very clear: when you call a function if it implicitly has a this (to point an object) and if you can't call the function without an object, the function deserves to name as method.

How come JavaScript {this} doesn't reference the parent object?

When making objects I assumed that this would return the object's instance - instead it seems it's something else. Why is this?
var Obj = {
foo : 'value',
bar : function() { return this.foo; } // Error
bar : function() { return Obj.foo; } // Works
}
Update: I must be missing something because in some cases using this inside objects doesn't work. How come this only references the object instance sometimes?
It does. You have a syntax issue.
Use commas to delimit object members
var Obj = {
foo : 'value',
bar : function() { return this.foo; },
}
within member functions this refers to a reference to the object that the function is called on.
jsFiddle Example
Within a JavaScript function this is set depending on how the function was called.
With your example Obj, assuming you correct the syntax error and use commas between properties:
var Obj = {
foo : 'value', // needs comma, not semicolon
bar : function() { return this.foo; }
}
If you use the "dot" syntax on Obj to call the bar function then this will be automatically set to Obj:
Obj.bar(); // this will be Obj
That's an easy way to ensure this ends up set the way you want. But if you call the function in some other way this could be set to something else:
var nonObjBar = Obj.bar; // get a reference to the function
nonObjBar(); // this will (probably) be `window`, but depends if
// in strict mode or inside some other function, etc
var Obj2 = { foo: "other foo" };
Obj.bar.call(Obj2); // the .call() method sets this to Obj2
// so bar will return Obj2's foo, "other foo"
That last example uses the .call() method on Obj.bar to invoke the function in a way that allows you to set this to anything you like (strict versus non-strict mode affects the way this works for some cases).
It might seem strange if you're coming from languages like Java, but JavaScript functions don't belong to any given object. This behaviour is pretty well defined and on purpose.
After fixing the semi-colon after 'value', this seems to work:
var Obj = {
foo : 'value',
bar : function() { return this.foo; } // Error
};
alert(Obj.bar()); // alerts 'value'
See working jsFiddle here: http://jsfiddle.net/jfriend00/UFPFf/.
When you call a method on an object, the javascript engine sets the this pointer to point to the object for the duration of the method call.
You shouldn't have a semicolon after foo.
Actually when you call Obj.bar you will have this referring to Obj.
See http://jsfiddle.net/AAkbR/
var Obj = {
foo : 'value',
bar : function () { return this.foo; }
};
alert(Obj.bar() === Obj.foo);
Alerts true.

Categories