We will give as an example the following code:
function A() {
this.atr1 = 1;
};
A.prototype = {atr2: 2, atr3: 3};
Function.prototype.atr4 = 4;
var a = new A();
In this code we have the following objects:
-
Constructor A : is a function that will be used as a constructor to create instances of new objects. Although being a function is also an object.
-
A.prototype : is the prototype object of A that is created automatically when you define function A. This object will be the ascending
__proto__
of any object instance created from from the constructor A.
-
Object to : is an instance of an object created from constructor A. This object will initially have attributes defined with
this
at the time of creation with new A()
since it executes the function A()
with this
the object a
newly created. Automatically the __proto__
of this object will be A.prototype
.
-
Function : It is the constructor function used implicitly in the creation of any function. Therefore, the prototype of
Function
( Function.prototype
) is automatically assigned as the __proto__
of any created function.
When trying to access an attribute of an object, JS first looks at whether that attribute is inside the object itself. If you can not find it, then start tracing the __proto__
parent successively until you find the attribute.
In this example, if I try to access a.atr2
, since this attribute is not within a
but yes in the __proto__
of a
( A.prototype
), it would return its value: 2.
The hasOwnProperty()
function checks if a property is inside an object, but only inside the object. If the property is not inside the object but is accessible through its __proto__
, the function hasOwnProperty()
would return false
.
Therefore, in your code you are trying to check if the A()
object has a series of direct properties and, as you can see, none of them is within A()
.
For that you should have done something like this: A.atr1 = 10
. Here atr1
would be an object property A()
, and return true
if A.hasOwnProperty("atr1")
is made.
Stop by here to better understand the subject of objects in JS. link