从java继承的角度来讲,子类extends父类之后,子类应该具有父类的public,protected访问权限限制的属性和方法.那在js中如何实现呢?
请看下面的例子:
<html>
<body>
<script type="text/javascript">
function Parent(name){
this.name = name || "default";
this.age=24;// Parent 独有的属性
this.wife = function(){ // Parent独有的属性
return "Parent's wife is my mother";
}
}
function Child(name,sex){
this.self=Parent; // 将Parent的引用赋值给当前对象本身
this.self(name); // 初始化Parent对象
delete this.self; // 删除当前对象的self
this.sex = sex || "M";
}
function test(){
var child = new Child("okgogogo","M");
alert(child.name);
alert(child.sex);
alert(child.age); // 此处结果为24,那么则说明Child继承了Parent
alert(child.wife()); // 此处结果为 :Parent's wife is my mother(额,其实这是一句P话)
}
</script>
<input type="button" value="click me" onclick="test()"></input>
</body>
</html>