JavaScript 方法和 this 关键字

x33g5p2x  于2022-04-18 转载在 Java  
字(1.9k)|赞(0)|评价(0)|浏览(290)

在本教程中,您将借助示例了解 JavaScript 对象方法和 this 关键字。
    在 JavaScript 中,对象也可以包含函数。例如,

// object containing method
const person = {
    name: 'John',
    greet: function() { console.log('hello'); }
};

在上面的示例中,person 对象有两个键( name 和 greet ),分别有一个字符串值和一个函数值。
    因此,JavaScript 方法基本上是一个具有函数值的对象属性。

访问对象方法

您可以使用点表示法访问对象方法。语法是:

objectName.methodKey()

您可以通过调用 objectName 和 key 来访问属性。可以通过调用 objectName 和该方法的 key 以及()来访问该方法。例如,

// accessing method and property
const person = {
    name: 'John',
    greet: function() { console.log('hello'); }
};

// accessing property
person.name; // John

// accessing method
person.greet(); // hello

在这里,greet 方法使用 person.greet() 访问,而不使用 person.greet 访问。
    如果您仅尝试使用 person.greet 访问该方法,它将为您提供一个函数定义。

person.greet; // ƒ () { console.log('hello'); }
JavaScript 内置方法

在 JavaScript 中,有许多内置方法。例如,

let number = '23.32';
let result = parseInt(number);

console.log(result); // 23

这里,Number 对象的 parseInt()方法用于将数字字符串值转换为整数值。
    要了解有关内置方法的更多信息,请访问JavaScript内置方法

向 JavaScript 对象添加方法

您还可以在对象中添加方法。例如,

// creating an object
let student = { };

// adding a property
student.name = 'John';

// adding a method
student.greet = function() {
    console.log('hello');
}

// accessing a method
student.greet(); // hello

在上面的示例中,创建了一个空的 student 对象。然后,添加 name 属性。类似地,还添加了 greet 方法。通过这种方式,可以向对象添加方法和属性。

JavaScript this 关键字

要从同一对象的方法中访问对象的属性,需要使用 this 关键字。让我们考虑一个例子。

const person = {
    name: 'John',
    age: 30,

    // accessing name property by using this.name
    greet: function() { console.log('The name is' + ' ' + this.name); }
};

person.greet();

输出

The name is John

在上面的示例中,创建了一个 person 对象。它包含属性(name 和 age)和方法 greet。
    在方法 greet 中,当访问该对象的属性时,使用关键字 this。
    为了访问对象的属性,在 this 关键字之后使用 . 和关键字。
    注意:在 JavaScript 中,当与对象的方法一起使用时,this 关键字指的是对象。this 已绑定到对象。
    然而,对象内部的函数可以以与普通函数类似的方式访问其变量。例如,

const person = {
    name: 'John',
    age: 30,
    greet: function() {
        let surname = 'Doe';
        console.log('The name is' + ' ' + this.name + ' ' + surname); }
};

person.greet();

输出

The name is John Doe

上一教程 :JS Object                                         下一教程 :JS Constructor Function

参考文档

[1] Parewa Labs Pvt. Ltd. (2022, January 1). Getting Started With JavaScript, from Parewa Labs Pvt. Ltd: https://www.programiz.com/javascript/methods

相关文章

微信公众号

最新文章

更多