0

这一直让我发疯!这是我第一次使用设置器和获取器,我很难过。

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();

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

4

1 回答 1

2

您的代码存在许多问题,您应该对其进行lint以查看您的语法错误。此外,您可能还想了解更多有关面向对象的 JavaScript的信息。

但是,这就是您要实现的目标(我认为):

演示: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());

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

这可以很容易地完成,但是由于您已经有一个Address值对象,因此该Person对象封装对象的实例Address而不是string.

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

于 2013-04-26T17:03:24.880 回答