javascrpt 代码复用之继承
程序员文章站
2022-07-15 14:22:09
...
参考资料:
《JavaScript 模式》(<< JavaScript Patterns >>)
中国电力出版社。Stoyan Stefanov著, 陈新 译。
1.原型继承;
var Main = {}; /** 原型继承 prototypal inheitance. */ Main.createObj = function(o){ function F() {}; F.prototype = o; return new F(); }; function Person(pName){ this.name = pName || "Adam"; }; Person.prototype.getName = function() { return this.name; }; Person.prototype.color = "red"; Main.testPrototypal = function(o){ var papa = new Person(); var kid = Main.createObj(papa); console.info(kid.getName()); console.info("kid-name:" + kid.hasOwnProperty("name")); console.info("kid-color:" + kid.hasOwnProperty("color")); console.info("kid-getName:" + kid.hasOwnProperty("getName")); console.info("papa-name:" + papa.hasOwnProperty("name"));// papa-name:true console.info("papa-color:" + papa.hasOwnProperty("color")); console.info("papa-getName:" + papa.hasOwnProperty("getName")); };
2. 通过复制属性实现继承;
2.1 浅复制
/** 复制属性实现继承--浅复制 (shallow copy)<br/> 修改子对象会 影响 父对象!! */ Main.extend = function(parent, child) { var i; child = child || {}; for (i in parent) { if (parent.hasOwnProperty(i)) { child[i] = parent[i]; } } return child; }; /** 浅复制 */ Main.testShallowCopy = function(){ console.info(" >>> Main.testShallowCopy"); var Car = { doors: [1,2,3,4], energy: {price: "$2.00"} }; var oneCar = Main.extend(Car); // 修改子对象会 影响 父对象!! oneCar.doors.push(9); // oneCar.doors, 1,2,3,4,9 console.info("oneCar.doors, " + oneCar.doors.toString()); // Car.doors, 1,2,3,4,9 console.info("Car.doors, " + Car.doors.toString()); };
2.2 深度复制
/** 复制属性实现继承--深度复制 (deep copy)<br/> */ Main.extendDeep = function(parent, child) { var i, toStr = Object.prototype.toString, astr = "[object Array]"; child = child || {}; for(i in parent) { if(parent.hasOwnProperty(i)){ if(typeof parent[i] === "object"){ child[i] = (toStr.call(parent[i]) === astr) ? []:{}; Main.extendDeep(parent[i], child[i]); }else{ child[i] = parent[i]; } } } return child; }; /** 深度复制 */ Main.testDeepCopy = function(){ console.info(" >>> Main.testDeepCopy"); var Car = { doors: [5,6,7,8], energy: {price: "$2.00"} }; var oneCar = Main.extendDeep(Car); // 修改子对象 不会影响 父对象!! oneCar.doors.push(1); // oneCar.doors, 5,6,7,8,1 console.info("oneCar.doors, " + oneCar.doors.toString()); // Car.doors, 5,6,7,8 console.info("Car.doors, " + Car.doors.toString()); };