javascript setter和getters

时间:2013-04-26 16:26:21

标签: javascript setter getter

这让我疯了!这是我第一次使用制定者和获得并且难以接受。

var Person = function () {
  var address = setPersonAddress();

  this.setPersonAddress = function (a.getFullAddress()) {
    address = a.getFullAddress();
  };
};

var Address = function () {
  var address = "xyz";
  var city = "xyz";
  var state = "NY";
  var zip = "56783";


  this.fullAddress = function () {
    var name = address + ", " + city + ", " + state + ", " + zip;
    return name;
  };

  this.getFullAddress = function () {
    return fullAddress();
  };
};

var a = new Address();

我正在尝试将Address对象的fullAddress分配给Person对象地址。我在setPersonAddress中正确引用了getFullAddress吗?

1 个答案:

答案 0 :(得分:2)

您的代码存在许多问题,您应lint查看语法错误。 此外,您可能想要阅读有关Object Oriented JavaScript的更多信息。

然而,这是你想要实现的目标(我认为):

DEMO: http://jsfiddle.net/FR8B8/

function Person(address) {
    this.setAddress(address);
}

Person.prototype = {
    setAddress: function (address) {
        this.address = address;
    },
    getAddress: function () {
        return this.address;
    }
};

function Address(fullAddress) {
    this.setFullAddress(fullAddress);
}

Address.prototype = {
    setFullAddress: function (fullAddress) {
        //naive parsing
        var addressParts = fullAddress.match(/(.+),(.+),(.+),(.+)/);

        this.fullAddress = fullAddress;
        this.address = addressParts[1];
        this.city = addressParts[2];
        this.state = addressParts[3];
        this.zip = addressParts[4];
    },

    getFullAddress: function () {
        return this.fullAddress;
    }
};

var a = new Address('15 test,Test City,Test State,J9A333'),
    p = new Person(a);

console.log(p.getAddress());
  

我正在尝试将Address对象的fullAddress分配给   人物对象地址。我正确地引用了getFullAddress   setPersonAddress?

这可以很容易地完成,但是因为你已经有了一个Address值对象,所以Person对象封装一个Address对象的实例而不是{{1 }}

从下面的示例中,您可以通过string获取某人的完整地址。请注意,可以在p.getAddress().getFullAddress()对象上创建一个getFullAddress函数成员,该成员封装此逻辑以简化操作。