无法访问Javascript对象中的变量

时间:2015-02-09 23:54:28

标签: javascript object javascript-objects

我不明白为什么我无法通过对象对象的全局函数中的 b c 变量进行访问,在变量继承方面遇到了一些麻烦JS对象。

var object = {

    a: 'a',

    global: function() {
        var b = 'b';
        this.c = 'c';
    },

    render: function() {
        console.log('render()');
        return this.a + ' / ' + this.global.b + ' / ' + this.global.c;
    }

};

呈现: a / undefined / undefined

I made a fiddle here

4 个答案:

答案 0 :(得分:2)

b是分配给global的函数的本地变量。它不是分配给object的对象的属性。

c是一个属性,在调用object后,设置在分配给object.global()的对象上。它不是分配给global的函数的属性。

如果您想要访问bc,那么您需要将该功能设为对象:

global: {
    b: 'b';
    c: 'c';
},

...或者使它们成为函数的属性......

global: function () {
    // The function can do something
},

// Outside the definition of object:

object.global.b = "b";
object.global.c = "c";

...或者您可以让函数返回它们,然后在调用函数后访问它们:

global: function () {
    return { b: "b", c: "c" };
},

// later

this.global().b;
this.global().c;

答案 1 :(得分:1)

B是全局的局部变量,而不是它的属性。并且c被明确定义为对象的属性,而不是全局属性。

答案 2 :(得分:1)

全球是一个功能。函数返回一些东西b只能在函数内访问,而不能从外部访问。同样适用于this.cthis.c!= global.c

看看这个。它将解释为什么bthis.c是范围global的私有变量:

var object = {

    a: 'a',

    global: function(which) {
        var b = 'b';
        this.c = "c";
        return {b:b, c:this.c}
        
    },

    render: function() {
        console.log('render()');
        return this.a + ' / ' + this.global().b + ' / ' + this.global().c;
    }

};

document.write(object.render())

在此示例中,函数global现在返回值。

答案 3 :(得分:1)

以这种方式尝试:

var object = {
    a: 'a',
    global: {
        this.b = 'b';
        this.c = 'c';
    },
    render: function() {
        console.log('render()');
        return this.a + ' / ' + this.global.b + ' / ' + this.global.c;
    }
};

在JavaScript中,范围很棘手,但是当您在函数内部声明一个带有var的变量时,它对该函数是私有的。例如:

function getValue(){
    var x=10;
    this.x=20;
    return x;
}

getValue();// Returns 10
new getValue().x;// Returns 20

this.x是“特权”,只能通过它所属的实例化对象访问。

var x是“私有”,它只能在其定义的函数/作用域内访问。