传值、传址、继承
传值和传址
基本数据类型(string,number,boolean)传值,复杂数据类型按引用传递(传址)
传值例:var a = 1; b = a; b++; 结果:a = 1,b = 2;
传址例:var a = [0, 1]; b = a; b.push(2); 结果:a = [0, 1, 2]; b = [0, 1, 2]
复制数组
//方法一 slice var a = [0, 1]; b = a.slice();
b.push(2);
alert(a+'|'+b); //0,1|0,1,2
//方法二 concat var a = [0, 1]; b = a.concat();
b.push(2);
alert(a+'|'+b); //0,1|0,1,2
//方法三 for in
var a = [0, 1], b = [];
for (var n in a){
b[n] = a[n]
}
b.push(2);
alert(a+'|'+b); //0,1|0,1,2
继承用例
function A(name){ this.name = name; } A.prototype.getName = function(){ return this.name; };
拷贝继承(简单版)
function extent(o, p){ for (var i in p){ o[i] = p[i]; } } // use function B(name){ A.call(this, name); } extent(B.prototype, A.prototype);
类式继承(适用于构造函数)
function B(name){ A.call(this, name); } // F为了只继承原型,避免引用相互影响 function F(){} F.prototype = A.prototype; B.prototype = new F(); B.prototype.constructor = B;
原型继承(适用于对象、JSON)
function cloneObj(o){ function F(){}; F.prototype = o; return new F(); } var a = {"name": "Jununx"}; var b = cloneObj(a);