About the problem of JS auxiliary function inherit () _ Basics

Source: Internet
Author: User
Tags gettext

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.