我有下面的代碼,當您使用this.
它的範圍是公共然而正在錯誤Uncaught TypeError: Object #<addThis> has no method 'returnValue' (anonymous function)
爲什麼我會收到錯誤消息對象在JavaScript中沒有方法?
function addThis() {
this.value1 = 1;
this.value2 = 2;
var returnValue = function() {
return (this.value1 + this.value2);
}
}
//Instantiate object and write response
var simpleObject = new addThis();
document.write(simpleObject.returnValue());
將'returnValue'指定爲'addThis'對象的屬性時,是否必須指定'this'關鍵字?我可以不只是'returnValue = ....'?如果不是,那爲什麼? – PeanutsMonkey
@PananutsMonkey:是的,當訪問屬性時,你總是必須指定對象,或者使用'this.propertyName'或'someVariable.propertyName'。範圍永遠不會像面向對象的語言那樣在對象內部。如果你使用'var returnValue = ...'它是一個局部變量,並且如果你只使用'returnValue = ...',那麼它就成爲一個全局變量(除非你在函數的其他地方有'var returnValue;') 。 – Guffa