11

JavaScript 对象方法

 1 year ago
source link: https://www.myfreax.com/javascript-object-methods/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
JavaScript 对象方法

JavaScript 对象方法

在本教程中,您将了解 JavaScript 对象方法以及如何为对象定义方法。

JavaScript 对象方法简介

对象是键/值对或属性的集合。当值是一个函数时,属性就变成了一个方法。通常,您使用方法来描述对象行为。

例如,以下将 greet 方法添加到 person 对象:

let person = {
    firstName: 'John',
    lastName: 'Doe'
};

person.greet = function () {
    console.log('Hello!');
}

person.greet();
Hello!

在这个例子中:

  • 首先,使用函数表达式定义一个函数,并将其赋值给对象 persongreet 属性。
  • 然后,调用 greet() 方法函数。

除了使用函数表达式之外,您还可以定义一个函数并将其分配给一个对象,如下所示:

let person = {
    firstName: 'John',
    lastName: 'Doe'
};

function greet() {
    console.log('Hello, World!');
}

person.greet = greet;

person.greet();

在这个例子中:

  • 首先,将 greet() 函数定义为普通函数。
  • 其次,将函数名称分配给 person 对象 greet 属性。
  • 最后、调用 greet() 方法。

对象方法简写

JavaScript 允许您使用对象字面量语法定义对象的方法,如以下示例所示:

let person = {
    firstName: 'John',
    lastName: 'Doe',
    greet: function () {
        console.log('Hello, World!');
    }
};

ES6 为您提供更加简洁的语法,允许您为对象定义方法:

let person = {
    firstName: 'John',
    lastName: 'Doe',
    greet() {
        console.log('Hello, World!');
    }
};

person.greet();

这种语法看起来更简洁,简单。

对象的 this

通常,方法需要访问对象的其他属性。例如,您可能想要定义一个方法,通过连接名字和姓氏来返回对象的全名。

在方法内部,this 值引用着对象,可以使用 this 调用对象的方法 。因此,您也可以使用 this 访问对象属性,如下所示:

this.propertyName

以下示例在 getFullName() 方法使用 this 访问对象属性 :

let person = {
    firstName: 'John',
    lastName: 'Doe',
    greet: function () {
        console.log('Hello, World!');
    },
    getFullName: function () {
        return this.firstName + ' ' + this.lastName;
    }
};


console.log(person.getFullName());
'John Doe'

你也可以阅读本教程获取关于 this 更多信息 。

你可以在任何时候为对象添加方法,可以使用使用 this 访问对象属性与和方法。当函数是对象的属性时,它就称为对象的方法。

微信公众号

支付宝打赏

myfreax 淘宝打赏

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK