2015-02-09 28 views
-1

我不明白爲什麼我可以通過bc。在目標對象的全局功能無法訪問變量,得到了一些麻煩,在JS對象變量繼承。無法訪問的變量在Javascript對象

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 /未定義/未定義

I made a fiddle here

+0

Global是一個函數。函數返回的東西。 'b'只能在函數內訪問,而不能從外部訪問。 'this.c'也一樣。 'this.c'!='global.c' – Mouser 2015-02-09 23:57:27

回答

2

b是一個局部變量分配給全局的功能。它不是分配給object的對象的屬性。

cobject.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; 
+0

謝謝,現在看來我更加清楚了。 – Sarcadass 2015-02-10 09:52:39

1

B是全局的局部變量,而不是它的一個屬性。並且c被明確定義爲對象的屬性,而不是全局屬性。

1

Global是一個函數。函數返回的東西。 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())

在這個例子中的全球功能現在返回值。

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是「private」,它只能在定義的函數/範圍內訪問。