函数中的getter和Setter(javascript) [英] Getters and Setters in a function (javascript)

查看:74
本文介绍了函数中的getter和Setter(javascript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在像这样的对象中使用get时,get有效:

When using "get" in an object like this, "get" works:

    var people = {
      name: "Alex",
      get sayHi() {
        return `Hi, ${this.name}!`
        }
    };

var person = people;

document.write(person.sayHi);

但是使用函数我收到错误。如何在这样的函数中使用Getters和Setter?

But with a function I get an error. How to use Getters and Setters in a function like this?

function People2() {
  this.name = "Mike";
  get sayHi() {
    return `Hi, ${this.name}!`;
  }
};

var user = new People2();

document.write(user.sayHi);

推荐答案

您可以使用实际的获取设置仅在类(ES2015)和对象文字中的关键字。

You can use the actual get and set keywords only in classes (ES2015) and object literals.

在ES5中,您通常会使用 Obect.defineProperty 来实现你想要实现:

In ES5, your would typically use Obect.defineProperty to implement what you're trying to achieve:

function People2() {
    this.name = "Mike";
}
Object.defineProperty(People2.prototype, "sayHi", {
    get: function() {
        return "Hi, " + this.name + "!";
    }
});



ECMAScript 2015



在ES2015中,你也可以使用类来实现所需的行为:

ECMAScript 2015

In ES2015, you could also use classes to achieve the desired behavior:

class People2 {
    constructor() {
        this.name = "Mike";
    }
    get sayHi() {
        return `Hi, ${this.name}!`;
    }
}

这篇关于函数中的getter和Setter(javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆