2017-06-27 9 views
-2

私は誤ってこのキーワードをsetter、getterメソッドの中で紛失しています。それはいくつかの奇妙なバグにつながる:(クローム、Firefoxでテストした)javascriptのsetter、getterメソッドに "this"というキーワードがありません

ケース1

let user = { 
    name: "John", 

    set fullName(value) { 
     name = value; 
    }, 

    get fullName() { 
     return name; 
    } 
}; 

user.fullName // "" 
user.fullName = "Batman" 
user.fullName // "Batman" 
user.name // "John" 

なぜまだ "ジョン" プロパティのですか? 「バットマン」はどこから来たのですか?

ケース2:上記のコードの変数名を変更し、何かが起こる:

let user = { 
    anythingButName: "John", 

    set fullName(value) { 
     anythingButName = value; 
    }, 

    get fullName() { 
     return anythingButName; 
    } 

    user.fullName // anythingButName is not defined at Object.get fullName [as fullName]... 
}; 

上記のコード内の変数には任意の名前が、単語を使用することはできません。どうしてか分かりません?

+3

console.log(window.name); –

答えて

1

どちらの場合も同じです。何が起こる:

let user = { 
    name: "John", 

set fullName(value) { 
    name = value;//sets window.name to *value* 
}, 

get fullName() { 
    return name;//returns window.name 
} 
}; 

console.log(
user.fullName,// window.name is "" by default 
window.name, 
user.fullName = "Batman", //=> window.name 
window.name, 
user.fullName, // "Batman" ==window.name 
user.name // "John" //what you really wanted 
); 

それだけとしてwindow.nameで(本当に)を作品冒頭で「」に設定されたデフォルトのプロパティ、したがって、ある。 次の場合にチェックインできます。

console.log(
    user.fullName, // undefined yet 
    user.fullName="test", 
    user.fullName // test 
); 
関連する問題