繁体   English   中英

无法访问Javascript对象中的变量

[英]Can't access variable in Javascript object

我不明白为什么我无法通过对象对象的全局函数中的bc变量进行访问,而在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

我在这里开小提琴

b是分配给全局函数的局部变量。 它不是分配给object

c在调用object.global()之后在分配给object的对象上设置的属性。 它不是分配给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;

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

全局是一种功能。 函数返回一些东西。 b仅可在函数内部访问,而不能从外部访问。 this.c this.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现在返回值。

尝试这种方式:

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是“ private”,只能在其定义的功能/范围内访问。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM