Recently read the JavaScript Authority Guide (Sixth Edition) in chapter sixth P122 has such a piece of code:
Copy Code code as follows:
Returns a new object that inherits from a proto property of a prototype object
Here you can use the Object.create () function of ES5
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 check further
if (t!== ' object ' && t!== ' function ') throw typeerror ();
var F = function () {}; Define an empty constructor
F.prototype = Proto; Set its prototype property to Proto
return new F (); To create an inherited object of Proto using F ()
}
Obviously the purpose of the helper function is to create a new object that inherits the parent class prototype
Problem
When it comes to the judgment of the following, one cannot understand
Copy Code code as follows:
var t = typeof Proto; Otherwise check further
if (t!== ' object ' && t!== ' function ') throw typeerror ();
Our impression that the prototype object should be an object or literal, then the type of parameter passed will have "function" type?
Understand
A function is also an object, and it can have its own properties and methods. Wait, this is not our static properties and methods Ah! This refers to the function as an object that can add attributes
Copy Code code as follows:
Test delivery function type
var func = function () {};
Func.text = ' good work ';
Func.gettext = function () {
return func.text;
};
Console.log (typeof func); ' function '
Passing a function type, returning a new object with Func as the prototype
var Subfunc = Inherit (func);
Console.log (Subfunc.gettext ()); Output: ' Good work '
Well, a proof of the statement. It turns out that the ' function ' type can be passed