Methods for JavaScript Object inheritance

Source: Internet
Author: User

Writing this topic is simply to take notes for yourself, or old forget.

The first method:

function fn1 (x) {this.x = x;        } function fn2 (x, y) {this.tmpobj = fn1;        This.tmpobj (x);        Delete this.tmpobj;    This.y = y; }

Second method: Call () or apply ()

function fn1 (x) {this.x = x;        } function fn2 (x, y) {Fn1.call (this, x);    This.y = y; }

Third method: Prototype chain inheritance

function fn1 (x) {this.x = x;    } fn1.prototype.y = function () {Console.log ("I Am pomelo");    } function Fn2 () {} Fn2.prototype = new fn1 ();    Fn2.prototype.constructor = fn2;    var fn2obj = new Fn2 (); Fn2obj.y ();

The most used is the second and the third type.

function fn1 (x) {this.x = x;    } fn1.prototype.z = function () {Console.log ("I Am pomelo");        } function fn2 (x, y) {fn1.apply (this, [x]);    This.y = y;    } Fn2.prototype = new fn1 ();    Fn2.prototype.constructor = fn2;    var fn2obj = new Fn2 (1024, 2048);    Console.log (fn2obj.x);    Console.log (FN2OBJ.Y); Fn2obj.z ();


Methods for JavaScript Object inheritance

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.