JavaScript optimized--09 mode (code reuse) 02

Source: Internet
Author: User
Tags shallow copy hasownproperty

prototype Inheritance://Modern No-Class inheritance mode

    • Basic code:
      var parent = {Name: "Papa"}var Child = object (parent); function Object (o) {function F () {}; F.prototype = O;return new F ();}

      When choosing inheritance, you can consider whether the incoming instance or the constructor prototype;

      var Child = object (parent), var child = object (Parent.prototype);
    • Implementation in ECMA5: Object.create ();

      var child = Object.create (parent, {age: {value:2}});

Implementing inheritance by copying properties

  • Shallow copy:
    function extend (parent, child) {var i;child = Child | | {};for (i in parent) {if (Parent.hasownproperty (i)) {child[i] = Parent[i];}} return child;}

    Problem: If the attribute is an object, it will still be affected;

  • Deep copy:
    function Extenddeep (parent, child) {var i,tostr = Object.prototype.tostring,astr = ' [Object Array] '; {};for (i in parent) {if (Parent.hasownproperty (i)) {if (typeof parent[i] = = = ' object ') {Child[i] = (Tostr.call (parent[i]) = = = Astr)? []: {};extenddeep (parent[i], child[i]);} else {Child[i] = Parent[i];}}} return child;}

  • Blending: Copies any member from multiple objects and makes these members a new object;

    function Mix () {var arg, prop, child = {};for (arg = 0; arg < arguments.length; arg + = 1) {for (prop in Arguments[arg]) { if (Arguments[arg].hasownproperty (prop)) {Child[prop] = Arguments[arg][prop];}}} return child;} var cake = Mix ({eggs:2, large:true},{butter:1, Salted:true},{flour: ' 3 cups '},{sugar: ' sure! '});

Borrowing method: reuse some methods, but do not want to form an inheritance relationship;

    • Use of Apply/call;
    • Use bind;

JavaScript optimized--09 mode (code reuse) 02

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.