2013-05-03 90 views
0

假设类似的代码。我想在某些函数somefunc中访问i和j。这将如何实现?如何访问javascript对象中的外部对象

var myObj = function(){ 
Object.defineProperty(this, 'j'){ 
get: function() { return 1;} 
}; 
} 

myObj.prototype = Object.create(null); 
myObj.prototype={ 
    constructor : myObj, 
    i : 1, 
    somefunc : function(){ 
     console.log(i + j); 
    } 
} 
+0

你尝试'this.i'和'this.j'?如果'somefunc()'没有在不同的上下文中调用(使用'call()'),它应该是对象本身。 – Simon 2013-05-03 08:24:43

回答

1

他们可以通过this.i访问和this.j

var myObj = function(){ 
    Object.defineProperty(this, 'j'){ 
     get: function() { return 1;} 
    }; 
} 

myObj.prototype = Object.create(null); 
myObj.prototype={ 
    constructor : myObj, 
    i : 1, 
    somefunc : function(){ 
     console.log(this.i + this.j); 
    } 
}