函数构造器构造对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function desc(){ } //返回对象类型原型的引用(就是给我们的对象添加属性和方法) desc.prototype={ name:"小明", age:18, like:function(){ alert('运动'); } } var a=new desc(); |
认识面向对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
//创建类 js中用函数来创建类 function animal(name){ var _this={} _this.name = name; _this.sayhello = function (){ alert("bhello"+ _this.name); } return _this; } //继承类 function dog(name){ var _this= animal(name); return _this; } var t=dog("hh"); t.sayhello(); |
如何复写父类中的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
//创建类 js中用函数来创建类 function animal(name){ var _this={} _this.name = name; _this.sayhello = function (){ alert("bhello"+ _this.name); } return _this; } //继承类 function dog(name){ var _this= animal(name); //父类方法 var supSay= _this.sayhello; //继承父类方法并重写 _this.sayhello= function(){ //获取animal中的方法,也就是继承方法 supSay.call(_this); alert("abhello"+_this.name); } return _this; } var t=dog("hh"); t.sayhello(); |
其中的代码这段:
1 2 3 4 |
_this.sayhello= function(){ alert("abhello"+_this.name); } |
完成了重写。
1 2 |
//获取animal中的方法,也就是继承方法 supSay.call(_this); |
完成了继承。
其中的call:
a(supSay是animal的sayHello)对象的方法应用到b(dog的_this)对象上(函数apply的意思正好说明符合这样理解:a对象应用到b对象上去)
a对象既然添加到b对象上了。那么b对象自然就拥有了a对象所有的内容。所有,b对象就继承了a对象了。结合自己编写的下面代码,理解怎么实现继承:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function class1() { this.name = function(){ alert("class1的方法name()"); } } function class2() { class1.call(this);//要想实现class2继承class1 this就是当前对象class2。 } //现在可以知道是否实现继承了: var cl = new class2(); cl.name();//class2继承了class1,class2是父类。调用父类的方法 |
赞