In fact, in JavaScript, all functions have access to the scope "above" them.
var z = 15;
var y= 3;
function test1(){
console.log(z); //15
var y = 100;
console.log("y:",y); //100
var x =5;
function test2(){
var y = 0;
}
}
test1();
console.log(x); // exception
test2(); //exception too
Functional Scope (即Local scope) 的注意事項-1
if(true){
var x = 3;
}
// 在其他某些語言裡, scope是block的, 即離開了{}變數會不存在.
// 但JavaScript是Functoinal scope的. Python也是
console.log("x:",x); //x:3
JavaScript Object的建立
Object Literal Notation.
var car = {name:"BMW", autoDrive:function(){}};.
較難重複製造並使用建立的屬性, 常用來用在屬性欄位不固定的case.
使用自定Function來自建物件類型(type, 有自己的名字). 使用new keyword.
function Car(){
this.name="";
this.setName=function(){
};
}
接著使用var car1 = new Car();方便重複使用. 較為接近一般語言裡的物件化的方法.
這方法較少用, 較難重複製造並使用建立的屬性.
var person = new Object();
person.firstName = "John";
var myModule = {
myProperty: 'someValue',
//object literals can contain properties and methods.
//here, another object is defined for configuration purposes.
myConfig: {
useCaching: true,
language: 'en'
},
// a very basic method
myMethod: function() {
console.log('I can haz functionality?');
//可以用 this 來存取其他的property
console.log('this.myProperty:', this.myProperty);
}
}
console.log(myModule.myConfig);
myModule.myMethod();
使用上除了直接指定為object的property外, e.g. obj.x=3, 有其他幾種宣告方式
var x = 3;.
x = 3;//前面沒有打var/let/const, 在Local scope這樣使用時, 若已有同樣名字的當然就是直接使用其Local變數. 若沒有, 則會變成global物件的屬性(宣告直接使用).
this.x = 3;
下面是此為function的物件化時的case.
// test in chrome console
// var y等於y等於this.y 在browser最上層
var y = 300;
y = 400;
console.log("this.y:", this.y); // 400
console.log("y:", y); // 400 !!!
console.log("this:", this); // will print many things
function TodoView() {
// Local:
// x: // 200
// this:
// x // 100
this.x = 100;
var x = 200;
console.log("this.x in TodoView:", this.x); // 100
console.log("x in TodoView:", x); //200
}
var xx = new TodoView();