This article introduces some questions about the JS auxiliary function inherit. I recently read the JavaScript authoritative guide (version 6) and have such a piece of code in Chapter 6 P122:
The Code is as follows:
// Return a new object that inherits the attributes of the prototype object proto.
// The ES5 Object. create () function can be used here
Function inherit (proto ){
// Proto is an object, but cannot be null
If (proto = null) throw TypeError ();
If (Object. create) return Object. create (proto); // if Object. create () exists, use it
Var t = typeof proto; // otherwise, further check
If (t! = 'Object' & t! = 'Function') throw TypeError ();
Var F = function () {}; // defines an empty constructor.
F. prototype = proto; // set its prototype property to proto
Return new F (); // use F () to create an inherited object of proto
}
Obviously, helper functions are used to create a new object that inherits the parent class prototype.
Problem
I cannot understand the following sentence at the moment.
The Code is as follows:
Var t = typeof proto; // otherwise, further check
If (t! = 'Object' & t! = 'Function') throw TypeError ();
In our impression, the original Object should be an Object or a literal. Will the passed parameter type be of the "function" type?
Understanding
Functions are also objects and can have their own attributes and methods. Wait, this is not our static property and method! This refers to the function as an object that can add attributes.
The Code is as follows:
// Test the function Transfer Type
Var func = function (){};
Func. text = 'good work ';
Func. getText = function (){
Return func. text;
};
Console. log (typeof func); // 'function'
// Pass the function type and return the new object based on func.
Var subFunc = inherit (func );
Console. log (subFunc. getText (); // output: 'good work'
Okay, a proof. It turns out that the 'function' type can be passed.