working with Object
javascript简单支持“面向对象”编程
定义对象的几种方式
第一种,直接创建对象,然后再给对象赋予属性和值:
var objectName = {}; objectName.prop1 = "xxx"; objectName.prop2 = "yyy";
第二种,创建对象的同时,赋予属性和值:
var objectName = { property1 : value1, property2 : value2, //..., propertyN : valueN };
比如,
var student = { name : "David Rayy", sclass : "VI", rollno : 12 }
第三种,使用构造函数创建对象
function student(name, sclass, rollno)
{
this.name = name;
this.sclass = sclass;
this.rollno = rollno;
}
//创建对象
studentv = new student("John", "V", 10);
studentvi = new student("Scott", "VI", 2);
访问/设置对象属性的两种方式:
dot notation
student.name = "David Rayy"; student.sclass = "V"; student.rollno = 1 ;
square bracket notation
student.["name"] = "David Rayy"; student.["sclass"] = "V"; student.["rollno"] = 1;
删除对象属性
var obj = { property1 : 'value1', property2 : 'value2', property3 : 'value3' }; obj.property1 = undefined; obj.property2 = null; delete obj.property3;
删除对象
myobj= new Array(element1, element2) delete myobj
为对象定义方法
var myObj = { ... methodName: Myfunction(parameters) { statements; } };
调用方法
myObj.methodName(parameters);
比如,
//定义一个方法 function studentDetails(stu) { alert(stu.name +","+stu.age); } //定义一个对象 function student(name, class, rollno) { this.name = name this.class = class this.class = rollno this.studentDetails = studentDetails//引用上面的方法为对象的方法 }
Prototype
javascript中任何对象都能找到它的prototype
一个对象将继承其prototype中定义的所有属性和方法
javascript虽然不支持继承,但是有了prototype,可变相支持对象的属性和行为的继承