Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

JavaScript对象 #93

Open Qingquan-Li opened 6 years ago

Qingquan-Li commented 6 years ago

JavaScript 对象

JavaScript 中的所有事物都是对象:字符串、数字、数组、日期、函数,等等。

JavaScript 中,对象是数据(变量),拥有属性和方法。对象是拥有属性和方法的数据。(在面向对象的语言中,属性和方法常被称为对象的成员)

例如:这样声明一个 JavaScript 变量时:

var txt = "Hello JavaScript";

实际上已经创建了一个 JavaScript 字符串对象。字符串对象拥有内建的属性 stringObject.length 和内建的方法 stringObject.indexOf(searchvalue,fromindex)

对象属性:

txt.length // 16

对象方法:

// indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。
txt.indexOf("Hello") // 0
txt.indexOf("He") // 0
txt.indexOf("e") // 1
txt.indexOf("JavaScript") // 6
txt.indexOf("javascript") // -1 没有则返回-1


JavaScript 创建对象

实例:

创建名为 "person" 的对象,并为其添加了四个属性:

// 创建名为 "person" 的对象
// 当使用关键字“new”声明变量时,该变量将创建为一个对象
person = new Object(); 
// 添加四个属性
person.firstname = "Fatli";
person.lastname = "Lee";
person.age = 22;
person.eyecolor = "black";

You define (and create) a JavaScript object with an object literal:

var person = {firstName:"Fatli", lastName:"Lee", age:22, eyeColor:"black"};
// Spaces and line breaks are not important. An object definition can span multiple lines:
var person = {
    firstName:"Fatli",
    lastName:"Lee",
    age:22,
    eyeColor:"black"
};


访问对象属性

// objectName.propertyName
person.firstName // "Fatli"

or

// objectName["propertyName"]
person["firstName"] // "Fatli"


访问对象方法

objectName.methodName()

实例:

var person = {
    firstName:"Fatli",
    lastName:"Lee",
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
};
person.fullName() // "Fatli Lee"