Home > Article > Web Front-end > What are prototype objects and prototype chains in js
In Javascript, everything is an object, but objects are also different, and they can be roughly divided into two categories, namely: Common object Object and Function object Function.
Generally speaking, The objects generated through new Function are function objects, and other objects are ordinary objects.
Example:
##12 |
##function f1 (){
## //todo
} var f2 = function(){
//todo
##}; var new Function( 'x' , 'console.log(x)' );
var new Object();
var new f1();
f1, //function
f2, //function
##typeoff3, //function
typeofo1, //object
typeofo2, //object
typeofo3
//object
##); <div class="line number21 index20 alt2">
<code class="csharp plain">>> function function function object object object
|
f1 is a function declaration, the most common way to define a function. f2 is actually an anonymous function. This anonymous function is assigned to f2, which is a function expression. Formula, f3 is not common, but it is also a function object.
Function is an object that comes with JS. When f1 and f2 are created, JS will automatically build these objects through new Function(). Therefore, these three objects are all through new Function() Created.
There are two ways to create objects in Javascript: object literals and using new expressions. The creation of o1 and o2 corresponds to these two ways. Let’s focus on o3. If you use Java and C# ideas To understand, o3 is an instance object of f1, and o3 and f1 are of the same type. At least I used to think so, but it is not the case...
So how do you understand it? Very simple, see if o3 passes new Function What is generated is obviously not, since it is not a function object, it is an ordinary object.
After a simple understanding of function objects and ordinary objects, let’s take a look at the prototype and prototype chain in Javascript:
In JS, whenever a function object f1 is created, the There are some attributes built into the object, including prototype and __proto__. prototype is the prototype object, which records some attributes and methods of f1.
It should be noted that prototype is invisible to f1, that is to say, f1 will not search for the properties and methods in prototype.
##123 | function f(){}
f.prototype.foo =
"abc" ;
console.log(f.foo);
//undefined
|
1234 | ##function f(){}
"abc" ;
obj = new f(); ##console.log(obj.foo); / /abc
|
The above is the detailed content of What are prototype objects and prototype chains in js. For more information, please follow other related articles on the PHP Chinese website!