首页 > 代码库 > JavaScript学习笔记三:JavaScript对象

JavaScript学习笔记三:JavaScript对象

一、前言

  • 对象的基本概念:Javascript提供了多个内建对象,比如String、Data、Array等等。对象指的是带有属性和方法的特殊数据类型
  • 创建对象:创建JavaScript对象主要有两种不同的方法:第一、定义创建对象的实例;第二,使用函数来定义对象,然后创建新的对象
  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"        "http://www.w3.org/TR/html4/loose.dtd"><html><head></head><body><script>    //创建直接的实例    persion = new Object();    persion.firstname = "Bill";    persion.lastname = "Gates";    persion.age = 56;    persion.eyecolor = "blue";    document.write(persion.firstname + " is " + persion.age + " years old.<br/>");    //替代语法(使用对象literals)    persion = {firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};    document.write(persion.firstname + " is " + persion.age + " years old.<br/>");    //使用构造器构造对象    function persionV(firstname,lastname,age,eyecolor){        this.firstname = firstname;        this.lastname = lastname;        this.age = age;        this.eyecolor = eyecolor;        //将方法添加到JavaScript对象中        this.changeName = changeName;        function changeName(name){            this.lastname = name;        }    }    myFather =  new persionV("Bill","GateV1",89,"red");    document.write(myFather.firstname + " is " + myFather.age + " years old.<br/>");    myFather.changeName("hehehe");    document.write(myFather.firstname + " " + myFather.lastname + " is " + myFather.age + " years old.<br/>");</script></body></html>

     

  • 访问对象的属性,属性指的是与对象相关的值,访问对象属性的语法如下:
    objectName.propertyName

    具体例子:

  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"        "http://www.w3.org/TR/html4/loose.dtd"><html><head></head><body><script>    var message = "Hello World!";    var x = message.length;    document.write(x)</script></body></html>

     

  • 访问对象的方法:方法指的是能够在对象上执行的动作,具体语法如下:
  • objectName.methodName()

    具体例子:

  • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"        "http://www.w3.org/TR/html4/loose.dtd"><html><head></head><body><script>    var message = "Hello World!";    var x = message.toUpperCase();    document.write(x)</script></body></html>

     

JavaScript学习笔记三:JavaScript对象