zoukankan      html  css  js  c++  java
  • JavaScript 对象

    JavaScript 对象

    对象只是一种特殊的数据。对象拥有属性方法

    访问对象的属性

    属性是与对象相关的值。

    访问对象属性的语法是:

    objectName.propertyName

    这个例子使用了 String 对象的 length 属性来获得字符串的长度:

    var message="Hello World!";
    var x=message.length;//12

    访问对象的方法

    方法是能够在对象上执行的动作。

    您可以通过以下语法来调用方法:

    objectName.methodName()

    这个例子使用了 String 对象的 toUpperCase() 方法来将文本转换为大写:

    var message="Hello world!";
    var x=message.toUpperCase();//HELLO WORLD!

    如何创建 JavaScript 对象?

    1、直接创建对象实例

    person=new Object();
    person.firstname="John";
    person.lastname="Doe";
    person.age=50;
    person.eyecolor="blue";

    或者

    person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};

    使用对象构造器创建对象

    函数构造器

    function person(firstname,lastname,age,eyecolor)
    {
    this.firstname=firstname;
    this.lastname=lastname;
    this.age=age;
    this.eyecolor=eyecolor;
    }

    从构造器创建新的对象实例

    var myFather=new person("John","Doe",50,"blue");
    var myMother=new person("Sally","Rally",48,"green");

    把属性添加到 JavaScript 对象

    您可以通过为对象赋值,向已有对象添加新属性:

    假设 personObj 已存在 - 您可以为其添加这些新属性:firstname、lastname、age 以及 eyecolor:

    person.firstname="John";
    person.lastname="Doe";
    person.age=30;
    person.eyecolor="blue";
    
    x=person.firstname;//John

    把方法添加到 JavaScript 对象

    方法只不过是附加在对象上的函数。

    在构造器函数内部定义对象的方法:

    //changeName() 函数 name 的值赋给 person 的 lastname 属性。
    function
    person(firstname,lastname,age,eyecolor){ this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; this.changeName=changeName; function changeName(name){ this.lastname=name; } } myMother=new person("Sally","Rally",48,"green"); myMother.changeName("Doe"); document.write(myMother.lastname);//Doe

    JavaScript for...in 循环

    var person={fname:"John",lname:"Doe",age:25}; 
    
    for (x in person) 
    { 
        txt=txt + person[x]; 
    }
     
     
  • 相关阅读:
    c++ 有序二叉树的应用
    c++ 二叉树的遍历
    c++ 创建二叉树
    c++ 双向链表 的查找和删除
    c++ 双向循环链表
    c++ 双向链表
    Jzoj4209 已经没有什么好害怕的了
    Jzoj4209 已经没有什么好害怕的了
    后缀自动机转后缀树模板
    后缀自动机转后缀树模板
  • 原文地址:https://www.cnblogs.com/baiyangyuanzi/p/6632030.html
Copyright © 2011-2022 走看看