Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: Assign method and string to the same property name

I know I'm going to get the people who say I simply shouldn't do this, but I am curious how people accomplish it.

I know I've seen where you can type the name of a property and get one value, but then you add the parenthesis to the end and it accesses a method.

Visually, I'm saying this:

foo returns 'bar'
foo() performs a function

The question is how?

like image 411
Adam Cook Avatar asked Aug 29 '15 22:08

Adam Cook


People also ask

What is @property in JavaScript?

A JavaScript property is a characteristic of an object, often describing attributes associated with a data structure. There are two kinds of properties: Instance properties hold data that are specific to a given object instance. Static properties hold data that are shared among all object instances.

How do you convert a string into an object property?

The only native Javascript function to convert a string into an object is JSON. parse() . For example, var parsed = JSON.

What is the difference between methods and properties in JavaScript?

Methods are like verbs. They perform actions. A property can't perform an action and the only value that a method has is the one that is returned after it finishes performing the action.

How do you assign a value to an object property?

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. It returns the target object which has properties and values copied from the target object.


1 Answers

This isn't possible, due to how properties are resolved on objects. This is the only thing that comes remotely close:

function f() {
  return 'I am being returned from the function.';
}

f.toString = function () {
  return 'I am a property on the variable.';
}

console.log('f() says: ' + f());
console.log('f says: ' + f);

It relies on the fact that JS typecasts functions via the .toString method in certain scenarios.

like image 75
sahbeewah Avatar answered Oct 12 '22 23:10

sahbeewah