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