如果我只有属性的引用,能否访问属性的对象?

4
我有一个变量包含一个对象属性的引用,是否可以访问该属性所属的对象?
2个回答

2
var obj = {
    p1: 1,
    p2: function(){
        return this;
    },
    p3: obj,
    p4: function() {
        return obj;
    }
}

// v1 is now integer, we cannot get actual `obj` from this `v1`
var v1 = obj.p1;

// `v2()` returns `window` object (or current context object), 
// so if `obj` is created only in global context (or current 
// context which you're calling `v2()`), you can get reference to `obj`
var v2 = obj.p2;

// as @Ignacio mentioned, you can use `v3` as reference to `obj`
var v3 = obj.p3;

// `v4()` also reference to `obj`
var v4 = obj.p4; 

2
除非属性值本身包含对该对象的引用,否则不会发生。

1
或包含一个可以返回该对象的函数的引用。 - Asad Saeeduddin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接