On: Prototype inheritance of javascript

Source: Internet
Author: User

Javascript inheritance is used in many frameworks, especially the original type inheritance. First, we need to understand a concept. What is original type inheritance? The so-called original type inheritance is to create a temporary constructor inside the function, then prototype the input object as the constructor, and finally return the new instance of this temporary type.

Please refer to the source code:

function clone(o) {    var F = function(){};    F.prototype = o;    return new F();}

 

First, let's take a look at the original type inheritance of ext (starting with row 4.1 of 1896.

var TemplateClass = function(){};var ExtObject = Ext.Object = {    chain: function (object) {        TemplateClass.prototype = object;        var result = new TemplateClass();        TemplateClass.prototype = null;        return result;    }}

The prototype of the object is cleared here.

Let's take a look at jquery's inheritance.

var jQuery = function( selector, context ) {        return new jQuery.fn.init( selector, context, rootjQuery );    };-----------------------jQuery.fn = jQuery.prototype = {    constructor: jQuery,    init: function( selector, context, rootjQuery ) {        -----------------------        }}-------------------jQuery.fn.init.prototype = jQuery.fn;

Jquery has a relatively high level of play. It can be done with jQuery. fn. init, but the idea is the same.

 

Situ's mass also have similar inheritance. Lines 17th in lang_fix.js:

create: function(o){            if (arguments.length > 1) {                $.log(" Object.create implementation only accepts the first parameter.")            }            function F() {}            F.prototype = o;            return new F();        }

 

I checked es5's official website and found its compatible patch:

 

// ES5 15.2.3.5// http://es5.github.com/#x15.2.3.5if (!Object.create) {    Object.create = function create(prototype, properties) {        var object;        if (prototype === null) {            object = { "__proto__": null };        } else {            if (typeof prototype != "object") {                throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");            }            var Type = function () {};            Type.prototype = prototype;            object = new Type();            // IE has no built-in implementation of `Object.getPrototypeOf`            // neither `__proto__`, but this manually setting `__proto__` will            // guarantee that `Object.getPrototypeOf` will work as expected with            // objects created using `Object.create`            object.__proto__ = prototype;        }        if (properties !== void 0) {            Object.defineProperties(object, properties);        }        return object;    };}

 

The above code is more comprehensive, but the patch of Object. defineProperties needs to be introduced separately, and the source code is more.

 

View Code

// ES5 15.2.3.6
// Http://es5.github.com/#x15.2.3.6

// Patch for WebKit and IE8 standard mode
// Designed by hax // Related issue: https://github.com/kriskowal/es5-shim/issues#issue/5
// IE8 Reference:
// Http://msdn.microsoft.com/en-us/library/dd282900.aspx
// Http://msdn.microsoft.com/en-us/library/dd229916.aspx
// WebKit Bugs:
// Https://bugs.webkit.org/show_bug.cgi? Id = 36423

Function doesDefinePropertyWork (object ){
Try {
Object. defineProperty (object, "sentinel ",{});
Return "sentinel" in object;
} Catch (exception ){
// Returns falsy
}
}

// Check whether defineProperty works if it's given. Otherwise,
// Shim partially.
If (Object. defineProperty ){
Var definePropertyWorksOnObject = doesDefinePropertyWork ({});
Var definePropertyWorksOnDom = typeof document = "undefined" |
DoesDefinePropertyWork (document. createElement ("div "));
If (! DefinePropertyWorksOnObject |! DefinePropertyWorksOnDom ){
Var definePropertyFallback = Object. defineProperty;
}
}

If (! Object. defineProperty | definePropertyFallback ){
Var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object :";
Var ERR_NON_OBJECT_TARGET = "Object. defineProperty called on non-object :"
Var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined" +
"On this javascript engine ";

Object. defineProperty = function defineProperty (object, property, descriptor ){
If (typeof object! = "Object" & typeof object! = "Function") | object = null ){
Throw new TypeError (ERR_NON_OBJECT_TARGET + object );
}
If (typeof descriptor! = "Object" & typeof descriptor! = "Function") | descriptor === null ){
Throw new TypeError (ERR_NON_OBJECT_DESCRIPTOR + descriptor );
}
// Make a valiant attempt to use the real defineProperty
// For I8's DOM elements.
If (definePropertyFallback ){
Try {
Return definePropertyFallback. call (Object, object, property, descriptor );
} Catch (exception ){
// Try the shim if the real one doesn't work
}
}

// If it's a data property.
If (owns (descriptor, "value ")){
// Fail silently if "writable", "enumerable", or "retriable"
// Are requested but not supported
/*
// Alternate approach:
If (// can't implement these features; allow false but not true
! (Owns (descriptor, "writable ")? Descriptor. writable: true) |
! (Owns (descriptor, "enumerable ")? Descriptor. enumerable: true) |
! (Owns (descriptor, "resumable ")? Descriptor. retriable: true)
)
Throw new RangeError (
"This implementation of Object. defineProperty does not" +
"Support retriable, enumerable, or writable ."
);
*/

If (supportsAccessors & (lookupGetter (object, property) |
LookupSetter (object, property )))
{
// As accessors are supported only on engines implementing
// '_ Proto _' we can safely override '_ proto _' while defining
// A property to make sure that we don't hit an inherited
// Accessor.
Var prototype = object. _ proto __;
Object. _ proto _ = prototypeOfObject;
// Deleting a property anyway since getter/setter may be
// Defined on object itself.
Delete object [property];
Object [property] = descriptor. value;
// Setting original '_ proto _ 'back now.
Object. _ proto _ = prototype;
} Else {
Object [property] = descriptor. value;
}
} Else {
If (! SupportsAccessors ){
Throw new TypeError (ERR_ACCESSORS_NOT_SUPPORTED );
}
// If we got that far then getters and setters can be defined !!
If (owns (descriptor, "get ")){
DefineGetter (object, property, descriptor. get );
}
If (owns (descriptor, "set ")){
DefineSetter (object, property, descriptor. set );
}
}
Return object;
};
}

// ES5 15.2.3.7
// Http://es5.github.com/#x15.2.3.7
If (! Object. defineProperties ){
Object. defineProperties = function defineProperties (object, properties ){
For (var property in properties ){
If (owns (properties, property) & property! = "_ Proto __"){
Object. defineProperty (object, property, properties [property]);
}
}
Return object;
};
}

EcmaScript6 class inheritance.

class module extends Base {    constructor() {    }}

The more you play, the more you like java, but es6 is not supported by many browsers.

 

The recommended statement is as follows:

if (!Object.create) {    Object.create = function create(o) {        var F = function(){};        F.prototype = o;        var result = new F();        F.prototype = null;        return result;    }}

 

Related Article

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.