Javascript实现继承的一种方法
边学边做,写写总结,给有用到的朋友,以少走弯路。不当之处请指正。
一、父对象:
Var A=function(arg){//父对象A的构造函数
this.var1=0;//公有变量
……
vary=f2();//调用“functionf2()”可在定义之前
varf1=function(){
};
function f2(){
}
var x=f1();//调用f1()必须在“var f1=function()”定义之后
};//A内部的内容在new A()时被创建,增大内存耗费
A.prototype={
init:function(arg1,arg2){
……
},
sayhello:function(){
}
};
二、子对象
var B=function(arg){
A.call(this.arg);//调用父对象(A对象)的构造函数
varvarB=this.var1;//A中公有变量得到继承、应用,varB为B中的私有变量
}
B.prototype=Object.create(A.prototype);//试了好几种,好象这种才象面向对象继承
B .prototype.constructor=B; //构造函数指到自身
结合jQuery 的扩展功能,扩展B的原型函数集
$.extend(B.prototype,{
setName:function(name){
},
sayhello:function(){
A.prototype.sayhello.apply(this,arguments);//调用父同名函数,好象call,apply皆可
//调用父类同名函数,见http://www.2cto.com/kf/201407/314654.html
……
}
});
三、应用
varb=new B(arg);
b.init();
b.setName(“张三”);
b.sayhello();
四、重要补充关于Object.create()
有的浏览器不支持Object.create(),自己写代码也是网上下的如下:
/
//**************************************************************************************
关于JS中"Object.create"的兼容实现(IE中不支持)https://segmentfault.com/q/1010000002919613
//*******************************************************************************************
if(typeof Object.create != 'function') {
//Production steps of ECMA-262, Edition 5, 15.2.3.5
//Reference: http://es5.github.io/#x15.2.3.5
Object.create= (function() {
// To save on memory, use a shared constructor
functionTemp() {}
// make a safe reference to Object.prototype.hasOwnProperty
varhasOwn = Object.prototype.hasOwnProperty;
returnfunction (O) {
// 1. If Type(O) is not Object or Null throw a TypeError exception.
if (typeof O != 'object') {
throwTypeError('Object prototype may only be an Object or null');
}
// 2. Let obj be the result of creating a new object as if by the
// expression new Object()where Object is the standard built-in
// constructor with that name
// 3. Set the [[Prototype]] internal property of obj to O.
Temp.prototype = O;
var obj = new Temp();
Temp.prototype = null; // Let's not keep a stray reference to O...
// 4. If the argument Properties is present and not undefined, add
// own properties to obj as ifby calling the standard built-in
// functionObject.defineProperties with arguments obj and
// Properties.
if (arguments.length> 1) {
// Object.defineProperties does ToObject on its first argument.
var Properties =Object(arguments[1]);
for (var prop inProperties) {
if (hasOwn.call(Properties, prop)) {
obj[prop] =Properties[prop];
}
}
}
// 5. Return obj
return obj;
};
})();
}
希望能帮到人。欢迎拍砖。