javascript的对象和构造函数
定义一个javascript对象可以这么定义
var a = {
x : 1,
y : 2,
add : function () {
return this.x + this.y;
},
mul : function () {
return this.x * this.y;
}
}
这样,你就定义了一个变量a,这个变量除了有x和y两个公有成员外,还有两个add和mul两个函数(公有方法)。但是这样的定义方法的缺点有2条:
1.批量生成对象很不方便,如果你var b=a;那么你每次修改b的成员,都会同时改掉a的成员,因为javascript的引用机制
2.如果每次生成对象需要自定义一些成员,都要写出相应的赋值操作,增加代码行数。
所以,在定义一个javascript对象之前,我们可以先定义一个构造函数。
function a(x, y) {
this.x = x;
this.y = y;
this.add = function () {
return this.x + this.y;
}
this.mul = function () {
return this.x * this.y;
}
}
然后,定义一个对象
a = new a(1, 2);
上面这句代码看起来简单,但是要和c++等面向对象的语言做个区分,a并不是严格意义上“类”的概念,因为javascript是没有类的,只是调用了构造函数而已。
现在问题来了,我们怎么实现继承?c++把封装,继承,多态这三个面向对象的特征实现得清清楚楚。但是对于javascript这样一个比较浪的语言,没有一个很严格的继承机制,而是采用以下几种方式来模拟。
javascript的prototype
为了能够讲清后面的apply或call函数,这里先引入prototype。prototype是只有function才有的。
要用好继承,首先要明白为什么要设计继承这个东西?无非就是“把公共的部分”提取出来,实现代码复用。
所以在javascript里,也是把公共部分放在function的prototype里。
我们来比较两个用prototype来实现继承的例子
function a(x, y) {
this.x = x;
this.y = y;
this.add = function () {
return this.x + this.y;
}
this.mul = function () {
return this.x * this.y;
}
}
function b(x,y){
}
b.prototype=new a(1,2);
console.log(new b(3,4).add());//3
这个例子中,子类的prototype指向一个a类对象
我们再实现一个b继承a的例子:
function a() {
}
a.prototype = {
x : 1,
y : 2,
add : function () {
return this.x + this.y;
},
mul : function () {
return this.x * this.y;
}
}
a.prototype.constructor=a;
function b(){
}
b.prototype=a.prototype;
b.prototype.constructor=b;
b的prototype对象引用了a的prototype对象,因为是引用,所以如果修改了b的prototype对象,a的prototype对象也随之修改,因为本质上他们都指向一块内存。所以每次改动b类型的prototype都要手动将constructor改回,防止错乱。相比两个例子,上一个例子因为没有引用,所以不会发生这个问题。
创建一个b类型的对象
b=new b();
b对象具有a类型的一切成员
console.log(b.add()); //3
因为每个prototype对象都有两个重要成员:constructor和_proto_,constructor本质上是一个函数指针,所以b.prototype=a.prototype执行后,覆盖掉了constructor,所以后面要让constructor重新指向b类型的构造函数。
javascript的构造函数绑定
在定义完一个a类型的构造函数后,再定义一个b类型,然后在b类型构造函数内部,“嵌入执行”a类型的构造函数。
function a(x, y) {
this.x = x;
this.y = y;
this.add = function () {
return this.x + this.y;
}
this.mul = function () {
return this.x * this.y;
}
}
function b(x, y, z) {
a.apply(this, arguments);
this.z = z;
}
console.log(new b(1,2,3));
apply函数和call函数基本一样,可以在b类型构造函数内部执行a类型构造函数。同时也可以继承a的所有成员。
显示结果:
这里给个公式:在b构造函数里写a.apply(this),可以让b构造出来的对象可以拥有a构造函数里的所有成员。
谈到apply和call,还可以实现多重继承
function ia(){
this.walk=function(){
console.log("walk");
}
}
function ib(){
this.run=function(){
console.log("run");
}
}
function person(){
ia.apply(this);
ib.apply(this);
}
var p=new person();
p.walk();//walk
p.run();//run
以上就是javascript中难点:prototype和构造函数绑定实例详解的详细内容。