2013-05-03 67 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); 
    } 
}