Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript对象 #93

Open
Qingquan-Li opened this issue Apr 22, 2018 · 0 comments
Open

JavaScript对象 #93

Qingquan-Li opened this issue Apr 22, 2018 · 0 comments

Comments

@Qingquan-Li
Copy link
Owner

JavaScript 对象

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

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

  • JavaScript 对象的属性:属性是与对象相关的值。 The name:values pairs (in JavaScript objects) are called properties.
  • 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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant