开发者

How to refer to the first object called?

开发者 https://www.devze.com 2023-01-27 11:53 出处:网络
I have this code: var Pers开发者_如何学Goon = { \"name\": \"\", \"changes\": { \"name to\": function(value) {

I have this code:

var Pers开发者_如何学Goon = {
 "name": "",
 "changes": {
  "name to": function(value) {
   this["name"] = value;
  }
 }
}

var Josh = Object.create(Person);
Josh["changes"]["name to"]("John");

console.log(Josh.name); // nothing
console.log(Josh.changes.name); // "John"

The problem is that this above refers to Object "changes" and not object instance "Josh".

I can't replace this with Person because then it's referring to the object "Person" and not to the object instance "Josh".

Is it possible to refer to Josh's name?


Why don't you use the more common form of Javascript OOP?

function Person() {
    this.name = "";
    this.changes = {};
    var _this = this;
    this.changes.nameTo = function(name) {
        _this.name = name;
    }
}

var Josh = new Person();
Josh.changes.nameTo("John");

console.log(Josh.name); // "John"
console.log(Josh.changes.name); // undefined


Sadly not. You don't have any reference to an enclosing instance of the object you're in currently. You need to move the method to the outer Person object.

var Person = {
 "name": "",
 "changeNameTo": function(value) {
   this["name"] = value;
 }
}

Edit: If you absolutely want the original structure, albeit strange from an OO perspective. You need to give the inner object a reference to the outer. Programatically you can do it as below - or perhaps do it in a constructor, depending on your framework providing the Object.create() method.

var Person = {
 "name": "",
 "changes": {
  "name to": function(value) {
   this.data["name"] = value;
  }
 }
}

var Josh = Object.create(Person);
Josh.changes.data = Josh;

Josh["changes"]["name to"]("John");
0

精彩评论

暂无评论...
验证码 换一张
取 消