读书人

JavaScript patterns 札记(一) 全局

发布时间: 2012-10-15 09:45:24 作者: rapoo

JavaScript patterns 笔记(一) 全局变量

myglobal ="hello"; // antipattern

console.log(myglobal); //"hello"

console.log(window.myglobal); //"hello"

console.log(window["myglobal"]);// "hello"

console.log(this.myglobal); //"hello"

?

function sum(x, y) {

// antipattern: implied global

result = x + y;

return result;

function sum(x, y) {

var result = x + y;

return result;

// antipattern, do not use

function foo() {

var a = b = 0;

// ...

functionfoo() {

var a, b;

// ...

a = b = 0;// both local

}

// definethree globals

varglobal_var = 1;

global_novar= 2; // antipattern

(function (){

global_fromfunc= 3; // antipattern

}());

// attempt to delete

deleteglobal_var; // false

delete global_novar; // true

delete global_fromfunc; // true

// test the deletion

typeof global_var; //"number"

typeof global_novar; //"undefined"

typeofglobal_fromfunc; // "undefined"

?

var global =(function () {

return this;

}());

?

读书人网 >JavaScript

热点推荐