當我定義「汽車」象下面,爲什麼/當我使用「this」時javascript如何訪問局部變量?
var Car = function(m) {
var model = m;
function getModel() {
return model;
}
return {
getModel : getModel
}
};
和我在這種情況下創建這樣var c1 = new Car("qwer");
一個對象,我無法訪問直接建模,僅通過關閉。
(console.log(c1.model); => undefined)
(console.log (c1.getModel()); => qwer)
,但是當我定義「汽車」像下面,
var Car = function(m) {
var model = m;
function getModel() {
return this.model;
}
return {
getModel : getModel
}
};
,我在這種情況下創建的對象var c2 = new Car("asdg");
,我無法訪問直接建模, 而且還關閉。
(console.log(c2.model) => undefined)
(console.log (c2.getModel() => undefined)
你能告訴我爲什麼會發生這種情況嗎?
因爲'this'指的是實例,並且沒有'model'實例變量......? 'model'是一個*局部變量*,基本上是私有的,而不是實例。同樣,從構造函數返回也不會做任何事情...... return語句被忽略,因爲構造函數不應該返回任何東西。 – Li357
我敢肯定有一個帖子解釋'this'' –
[here's one](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work/3127440#3127440) – Reyno