JavaScript Object defineProperties和max

Ado*_*dis 0 javascript oop getter-setter

我正在学习JavaScript中的OOP基础知识,我在这个例子中遇到了一些问题:

var Human = function (first, surname) {
    var x = {};
    Object.defineProperties(x, {
        first: {
            get: function () {
                return this.first;
            },
            set: function (value) {
                this.first = value;
            }
        },
        surname: {
            get: function () {
                return this.surname;
            },
            set: function (value) {
                this.surname = value;
            }
        }
    });
    return x;
};
var alex = new Human("Alex", "Corlette");
Run Code Online (Sandbox Code Playgroud)
  1. 这:console.log(alex);输出:

    {}

  2. 这个:console.log(alex.first);输出:

    未捕获RangeError:超出最大调用堆栈大小

任何人都知道我做错了什么?

Dea*_*ady 7

问题在于范围.因为您正在定义一个属性,并且在getter和setter中引用了那些相同的getter和setter.

可以通过删除this关键字来修复该示例.

var Human = function (first, surname) {
  var x = {};
  Object.defineProperties(x, {
    first: {
        get: function () {
            return first;
        },
        set: function (value) {
            first = value;
        }
    },
    surname: {
        get: function () {
            return surname;
        },
        set: function (value) {
           surname = value;
        }
    }
  });
  return x;
};
var alex = new Human("Alex", "Corlette");
Run Code Online (Sandbox Code Playgroud)