Object-Oriented JavaScript 笔记
Object-Oriented JavaScript笔记(一)
Object-Oriented JavaScript笔记(二)
Object-Oriented JavaScript笔记(三)
Object-Oriented JavaScript笔记(四)
Object-Oriented JavaScript笔记(五)
Object-Oriented JavaScript笔记(六)
Object-Oriented JavaScript笔记(七)
第六章 继承
空的构造函数—new F()
用于解决原型链上的属性被覆盖的问题。
var extend = function(origin, target){ var F = function(){}; F.prototype = origin.prototype; target.prototype = new F(); target.prototype.constructor = target; }; var A = function(){}; A.prototype.name = 'A'; A.prototype.toString = function(){ return this.name}; var B = function(){}; extend(A,B); B.prototype.name = 'B'; /* var a = new A(); var b = new B(); b instanceof B true b instanceof A true a instanceof A true a instanceof B false */ |
Uber 访问父方法。
var extend = function(origin, target){ var F = function(){}; F.prototype = origin.prototype; target.prototype = new F(); target.prototype.constructor = target; target.uber = origin.prototype; }; var A = function(){}; A.prototype.name = 'A'; A.prototype.toString = function(){ var result = []; if (this.constructor.uber){ result[result.length] = this.constructor.uber.toString(); } result[result.length] = this.name; return result.join(', '); }; A.prototype.show = function(){ console.log('A show'); }; var B = function(){}; extend(A,B); B.prototype.name = 'B'; B.prototype.show = function(){ this.constructor.uber.show(); console.log('B show'); }; /* var a = new A(); var b = new B(); b instanceof B true b instanceof A true a instanceof A true a instanceof B false */ |
用函数来实现继承 (注:实际上上面的两个示例的extend已经是被我封装过的了)
var exntend = function(Child, Parent){ var F = function(){}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.uber = Parent.prototype; }; |
复制属性
function extend2(Child, Parent) { var p = Parent.prototype; var c = Child.prototype; for (var i in p) { c[i] = p[i]; } c.uber = p; } |
当复制引用带来的问题
修改引用对象会导致原型的也被修改。
从对象中继承:
浅拷贝
function extendCopy(p) { var c = {}; for (var i in p) { c[i] = p[i]; } c.uber = p; return c; } |
深拷贝:
function deepCopy(p, c) { var c = c || {}; for (var i in p) { if (typeof p[i] === 'object') { c[i] = (p[i].constructor === Array) ? [] : {}; deepCopy(p[i], c[i]); } else { c[i] = p[i]; } } return c; } |
object()构造起,老道提议的形式。
function object(o) { function F() {} F.prototype = o; return new F(); } |
混合原型拷贝和属性继承(很多时候需要继承一个对象,并给它添加一些属性用)
function objectPlus(o, stuff) { var n; function F() {} F.prototype = o; n = new F(); n.uber = o; for (var i in stuff) { n[i] = stuff[i]; } return n; } |
多重继承,说白了就是按顺序进行属性复制,后出现的覆盖已经存在的。
function multi() { var n = {}, stuff, j = 0, len = arguments.length; for (j = 0; j < len; j++) { stuff = arguments[j]; for (var i in stuff) { n[i] = stuff[i]; } } return n; } |
-EOF-