如何在对象文字函数中访问this.var

时间:2018-02-26 13:26:51

标签: javascript

我遇到过这段代码

var person = {
    name: "joseph",
    age: 33,
    favSong: function killingInTheTameOf(){
        this.lyrics = "Those who died are justified";
    }
};

document.write(person.lyrics); //doesn't work

我的问题是 this.lyrics 变量,
这是什么意思?
我该如何访问它? 这究竟是指什么?人?
我已经读过这个,但我所了解的案例都没有涵盖这个

1 个答案:

答案 0 :(得分:0)

您需要致电favSong以创建属性lyrics

var person = {
    name: "joseph",
    age: 33,
    favSong: function killingInTheTameOf(){
        this.lyrics = "Those who died are justified";
    }
};

person.favSong();
document.write(person.lyrics); //worksss