cc.js.extend
2019-06-20 本文已影响0人
凡凡的小web
Extend
// 例子:浅拷贝
var a = {};
var b = {c:1, d:2};
for(var i in b){
a[i] = b[i];
}
// 封装,对引用类型(数组、对象)没有用
function extend(sub,sup){
for(var i in sup){
sub[i] = sup[i];
}
}
继承
var People = function (){
this.name = 'rzy';
}
People.prototype.getName = function(){
return this.name;
}
var Man = function (){
this.sex = 'male';
People.call(this);
}
/* 土鳖方法,加入后期People中的name改变了,那Man的值也会改变
Man.prototype = People.prototype;
var man = new Man();
man.getName(); // rzy
*/
Man.prototype = new People();
Man.prototype.constructor = Man;
var man = new Man();
man.getName(); // rzy
示例
// ------------ Base class ----------------
let BaseCls = function () {
this.name = "base class";
this.ok = true;
};
BaseCls.prototype.printName = function () {
console.log(this.name);
};
// ------------ Ext class ----------------
let ExtCls = function () {
BaseCls.call(this);
this.name = "Ext class";
};
// extend before set new prototype functions, avoid override by extend()
cc.js.extend(ExtCls, BaseCls);
// set new prototype
ExtCls.prototype.printName = function () {
BaseCls.prototype.printName.call(this);
console.log("==== ext add info ===");
console.log(this.ok);
};
var bs = new BaseCls();
bs.printName();
var ex = new ExtCls();
ex.printName();
输出:
base class
Ext class
==== ext add info ===
true
原文:https://blog.csdn.net/ruizhengyun/article/details/43537371
http://www.tyrantek.com/archives/579/