Javascript Function Properties

Why can I do the following in javascript:

function a() {}; a.foo = 30; 

In particular, why can I set the property to function a? In the end, I cannot do this:

 var a = 20; a.foo = 30; 
+4
source share
4 answers

You really cannot do this because it is a syntax error

 function a = function() {}; 

I guess you just want to say:

 function a() {} 

Anyway. The reason you cannot get a property from a number is because it is not a real object.

 a = 20; a.foo = 30; // this works alert(a.foo); // this alerts nothing 

Believe it or not, the same goes for the lines:

 a = "ohai"; a.foo = 30; // this works alert(a.foo); // this alerts nothing 

However, if it is a String object, it works as expected:

 a = new String("ohai"); a.foo = 30; // this works alert(a.foo); // this alerts 30 

Or, if it is a Number object. You understand.

String and number literals are not objects in Javascript. This is the reason.

+6
source

In JavaScript, the dot ( . ) Operator expects this value to remain an object. And in JavaScript, functions are objects.

Basically, there are four main data types in JavaScript:

  • room
  • Line
  • Boolean
  • An object

Objects include functions, arrays, date objects, and (due to the lack of a better word) ordinary objects. A function object is unique in that it contains executable code and can be called .

Numbers are primitives, and therefore you cannot access / assign properties to / from them.

+4
source

In Javascript, a function is an object, so you can set properties on it:

 function a() {}; a.foo = 30; a.foo; // evaluates to 30 

However, a numeric literal creates a primitive value (which has no properties), not an object.

 a = 20; // Create primitive value using number literal 

When you set a property to a primitive value, you actually create a wrapper around the primitive value and set the property to the wrapper, not the primitive value.

 a.foo = 30; // wrapper object created and directly thrown away (new Number(a)).foo = 30; // --> equivalent 

When you read a property, you again create a wrapper object that does not have a specific property.

 a.foo; // wrapper object created, has no foo property (new Number(a)).foo; // --> equivalent, evaluates to undefined 
+2
source

There are objects in javascript functions. Or they inherit from objects or something like that.

try to do

 a = function(){}; alert(typeof a.prototype); 
0
source

All Articles