w3r-javascript08: Objects

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,可变相支持对象的属性和行为的继承

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值