开发者

Is this a safe way to reference objects in JavaScript?

If I were to define two objects myDataStore and myDrawer something like this:

var myDataStore = function(myObjectRef) {
    this.myInternalObject = myObjectRef;
};

var myDrawer = function(myObjRef) {
    this.myInternalObject = myObjectRef;
};

And if I were to create an object like so:

[[EDIT - Adjusted Object Creation to Ensure 'this' is being mapped to myObject, not the global window object]]

(function(){
  var myObject = window.myObject = function(){
      this.dataStore = new myDataStore(this);
      this.drawer = new myDrawer(this);
  }
 })();

Then myObject.dataStore.myInternalObject, and myObject.drawer.myInternalObject, would simply be pointers back to the original 'myObject' - not taking up开发者_开发知识库 any additional memory in the browser. Yes?

I am interested in implementing techniques like this - as it makes it easy for objects to communicate with each other.


Nope. this refers to whatever is on the left hand side of the . or if there is no left hand side of the . then it's the global object.

So if you did this:

var MyObj = {
   "create": function() {
      var myObject = {
         dataStore = new myDataStore(this);
         drawer = new myDrawer(this);
      }; 
   }
}; 
MyObj.create();

this would be MyObj. If you did this:

var myObject = {
   dataStore = new myDataStore(this);
   drawer = new myDrawer(this);
}; 

(not in a function) this would be window (assuming this is in a browser).


Yes, your assumption is correct. myInternalObject will be a reference and not a new object. You can test it like this:

var MyDataStore = function(myObjectRef) {
    this.myInternalObject = myObjectRef;
};

var data = {
    value: "value"
};
var dataStore = new MyDataStore(data);
data.value = "test";
console.log(dataStore.myInternalObject);  // logs { value : "test" } instead of { value: "value" }


No. myObject.dataStore.myInternalObject and myObject.drawer.myInternalObject will both point to the global object (mapped to window in browsers), unless you're inside a function already when you declare myObject. In other words, it will be set to whatever this is in the context in which you declare myObject. It won't be myObject itself.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜