Home > Web Front-end > JS Tutorial > Questions about JS auxiliary function inherit()_Basic knowledge

Questions about JS auxiliary function inherit()_Basic knowledge

WBOY
Release: 2016-05-16 17:38:19
Original
1047 people have browsed it

I was recently reading "The Definitive Guide to JavaScript (Sixth Edition)" and there is this code in Chapter 6 P122:

Copy code The code is as follows:

// Returns a property inherited from the prototype object proto New object
//You can use the ES5 Object.create() function here
function inherit(proto) {
//proto is an object, but it 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(); // Use F() to create an inherited object of proto
}

Obviously the purpose of the helper function is to create a new object that inherits the prototype of the parent class

Question

I can’t understand the following judgment for the moment

Copy code The code is as follows:

var t = typeof proto; // Otherwise check further
if(t!=='object' && t!=='function') throw TypeError();

In our impression, the prototype object should be an Object or directly a literal, so will the passed parameter type have a "function" type

Understand

Functions are also objects and can also have their own properties and methods. Wait, these are not our static properties and methods! This refers to treating functions as objects that can add attributes

Copy code The code is as follows:

// Test passing function 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 a new object prototyped with 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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template