JavaScript - this of this

后端 未结 2 2139
甜味超标
甜味超标 2021-02-20 01:27
String.prototype.foo = {};
String.prototype.foo.bar = function() {
    //How can you reference the \"grandparent\" string?
    console.log(this.parent.parent); //obvious         


        
2条回答
  •  心在旅途
    2021-02-20 02:23

    There is no way for an object to know what object it's a property of. The same object (in your case a function) could be attached to multiple objects. Here's an example:

    var myObj = {};
    var objA = {prop: myObj};
    var objB = {nother: myObj}
    

    If given a reference to myObj, how could you possibly know which parent object you're referring to? In one case, it's nothing, another case, it's objA, the last case, it's a 'child' object of objB. If you explain why you'd like this behavior, we can help you solve the problem at hand. But the answer to the question is that you CAN'T do it.

提交回复
热议问题