JavaScript中定义对象的几种方式(JavaScript中没有类的概念,只有对象)
原型(“prototype”)
使用原型+构造函数方式来定义对象 对象之间的属性互不干扰,各 个对象间共享同一个方法
function Person()
{ this.username = new Array();
this.password = "123";
}
Person.prototype.getInfo = function()
{
alert(this.username + ", " + this.password);
}
var p = new Person();
var p2 = new Person();
p.username.push("zhangsan");
p2.username.push("lisi");
p.getInfo();
p2.getInfo();
JavaScript中的继承。
1) 对象冒充
2) call方法方式
Parent.call(this, username);
call方法是Function对象中的方法,因此我们定义的每个函数都拥有该方法。可以通过函数名来调用call方法,call方法的第一个参数会被传递给函数中的this,从第2个参数开始,逐一赋值给函数中的参数。
3) apply方法方式
Parent.apply(this, new Array(username));
4)原型链方式(无法给构造函数传参数)
prototype
5)混合方式(推荐)
function Parent(hello)
{ this.hello = hello; }
Prent.prototype.sayHello = function()
{ alert(this.hello); }
function Child(hello, world)
{ Parent.call(this, hello);
this.world = world;
}
Child.prototype = new Parent();
Child.prototype.sayWorld = function()
{ alert(this.world); }
var child = new Child("hello", "world");
child.sayHello();
child.sayWorld();
JavaScript事件
onclick onmouseover onmouseout
onabort | 图片下载被打断时 |
onblur | 元素失去焦点时 |
onchange | 框内容改变时 |
onclick | 鼠标点击一个对象时 |
ondblclick | 鼠标双击一个对象时 |
onerror | 当加载文档或图片时发生错误时 |
onfocus | 当元素获取焦点时 |
onkeydown | 按下键盘按键时 |
onkeypress | 按下或按住键盘按键时 |
onkeyup | 放开键盘按键时 |
onload | 页面或图片加载完成时 |
onmousedown | 鼠标被按下时 |
onmousemove | 鼠标被移动时 |
onmouseout | 鼠标离开元素时 |
onmouseover | 鼠标经过元素时 |
onmouseup | 释放鼠标按键时 |
onreset | 重新点击鼠标按键时 |
onresize | 当窗口或框架被重新定义尺寸时 |
onselect | 文本被选择时 |
onsubmit | 点击提交按钮时 |
onunload | 用户离开页面时 |
JavaScript 对象化编程
基本对象
String 字符串对象 Array 数组对象 Math “数学”对象 Date 对象
文档对象
navigator screen window history location document