JavaScript prototype 属性
2018-05-14 本文已影响4人
追逐_chase

prototype 属性允许您向对象添加属性和方法 , Prototype 是全局属性,适用于所有的Javascript对象。
- 给数组对象 扩充一个run方法,只要创建不同的实例对象都可以调用run这个方法
//原型
Array.prototype.run = function () {
console.log("开奔驰");
}
var arr = [];
arr.run();
var arr1 = [];
arr1.run();
- this是指向事件的调用者
<script type="text/javascript">
//获取对象 遍历对象 操作显示 隐藏显示
//创建构造函数
function List(id) {
this.id = document.getElementById(id);
this.lis = this.id.children[0].children;
}
//初始化
List.prototype.init = function () {
var that = this;
for (var i = 0; i < that.lis.length; i ++){
that.lis[i].index = i;
that.lis[i].onmouseover = function () {
that.show(this.children[0]);
}
that.lis[i].onmouseout = function () {
that.hide(this.children[0]);
}
}
}
//操作显示
List.prototype.show = function (obj) {
obj.style.display = "block";
}
//操作隐藏
List.prototype.hide = function (obj) {
obj.style.display = "none";
}
//创建对象
var list = new List("list");
list.init();
</script>