您的位置:首页 > 移动开发

JavaScript原型、函数伪装(apply,call)、继承

2015-12-26 14:22 776 查看
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原型与继承</title>
<script type="text/javascript">
/*
* 组合的方式是属性通过伪造的方式实现,方法通过原型链的方式实现,注意内存模型
*
*
* */
function Parent(name) {
this.name = name;
this.color = ["red", "blue"];

}

Parent.prototype.ps = function () {

alert(this.name + "[" + this.color + "]");
}

function Child(name, age) {
this.age = age;
Parent.call(this, name);

}

Child.prototype = new Parent();
Child.prototype.say = function () {
alert(this.name + "," + this.age + "[" + this.color + "]");
}

var c1 = new Child("Leon", 22);
c1.color.push("green");
c1.say();
c1.ps();
var c2 = new Child("Ada", 23);
c2.say();
</script>
</head>
<body>

</body>
</html>


通过原型的方式创建对象:
/*
*使用基于原型的方式创建可以将属性和方法设置为Person专有的,不能通过windows来调用
*
* */

function Person(){

}

Person.prototype.name="Leon";
Person.prototype.age=23;
Person.prototype.say=function(){

alert(this.name+","+this.age);
}
var p1=new Person();
p1.say();
say();
//以下方法可以检测出p1 是否有_prop_隐藏属性指向Person的原型
alert(Person.prototype.isPrototypeOf(p1));





参考视频:原型内存模型
http://tianxingzhe.blog.51cto.com/3390077/1728556
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js 继承