标签:
javaScript中并不存在继承的感念..但是我们可以根据javaScript的原型进行模拟JavaScript的"继承":
1.写两个函数对象,将其中的一个函数赋值给另一个函数对象的原型:
<script type="text/javascript">
function A(){
this.a = "a";
this.sayA = function(){
alert("this is a.");
}
}
var a = new A();
function B(){
this.b = "b";
this.sayB = function(){
alert("this is b.");
}
}
B.prototype = a;
//测试:函数对象B就"继承"了函数对象A
var b = new B();
alert(b.b);
b.sayB();
alert(b.a);
b.sayA();
</script>运行结果:
2.只继承于原型(定义A的函数对象,定义A函数对象的原型.定义B函数对象,把A对象的函数原型赋值给B的原型)
function A(){}
A.prototype = {
a : "a",
sayA : function(){
alert("this is a.")
}
}
function B(){
this.b = "b";
this.sayB = function(){
alert("this is b.");
}
}
B.prototype = A.prototype;
var b = new B();
alert(b.b);
b.sayB();
alert(b.a);
b.sayA();<script type="text/javascript">
function A(){}
A.prototype = {
a : "a",
sayA : function(){
alert("this is a.")
}
}
function B(){}B.prototype = A.prototype;
B.prototype.b = "b";
B.prototype.sayB = function(){
alert("this is b.")
}
var b = new B();
alert(b.a);
b.sayA();
alert(b.b);
b.sayB();
</script>
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u014010769/article/details/46955841