读书人

js 常识小结(一)

发布时间: 2012-11-05 09:35:11 作者: rapoo

js 知识小结(一)
一、修改对像而生成新的对象1 SCRIPTLANGUAGE="JavaScript">2 !--3 varitem="test"; 4 varitemRef=item; 5 alert(item); 6 item+="ing"; 7 alert(item); 8 alert(itemRef); 9 //--> 10 /SCRIPT>
二、typeof 类型检查1 if(typeofnum=="string"){ 2 num=parseInt(num); 3 }4 if(typeofarr="string"){ 5 arr=arr.split(","); 6 }1 if(num.constructor==String){ 2 num=parseInt(num); 3 }4 if(str.constructor==Array){ 5 str= str.join(","); 6 }图 1-1变量typeof 变量变量.构造函数

{an:object}

object

Object

[an:”array”]

object

Array

function() {}

function

Function

“a String”

string

String

55

number

Number

true

boolean

Boolean

new User()

object

User

三、作用域

注意: 在javascript中,作用域是有函数划分的,而不是由块(比如: while, if 或for语句) 划分的。

1 varflag="old"; 2 if(true){ 3 varflag="new"; 4 }5 alert(flag=="new"); 6 ?7 //function 8 functiontest(){ 9 varflag="old"; 10 }11 test(); 12 alert(flag=="new");

说明:所有属于全局作用域的变量 其实都是 window对象的属性(property).

1 vartemp="howareyou?"; 2 alert(window.temp==temp); 3 //true


隐式全局作用域变量的声明:

1 //------------------ 2 //temp未用var声明 3 //alert(window.temp==temp);true 4 functiontest(){ 5 temp="1111"; 6 }7 test(); 8 alert(window.temp==temp); 9 //------------------ 10 //temp用var声明 11 //缺少对象temp为局部变量 12 functiontest(){ 13 vartemp="2222"; 14 }15 test(); 16 alert(window.temp==temp);

?

四、闭包

闭包意味着内层的函数可以引用包围它的函数内的变量,即使外层函数的执行已经终止。

JS中的CURRY化技术: curry化是通过把多个参数填充到函数体中,实现将函数转换为一个新的经过简化的(便之接受的参数更少)函数的技术

1,用闭包实现的函数 curry化:

1 functionaddGenerator(num){ 2 //返回一个简单的函数,求两个数的和,其中第一个数字来自生成器 3 returnfunction(toAdd){ 4 returnnum+toAdd; 5 }; 6 } 7 varaddFive=addGenerator(5); 8 alert(addFive); 9 //9

?

五、上下文对象

在javascript中,你的代码总是有一个上下文对象(代码处在改对象内)。上下文对象是通过this变量体现的,这个变量永远指向当前代码处的对象中。

1 varobj={ 2 yes:function(){ 3 this.val=true; 4 }, 5 no:function(){ 6 this.val=false; 7 } 8 } 9 alert(obj.val==null); 10 obj.yes(); 11 alert(obj.val==null); 12 //现在把window.no指向obj.no并执行之 13 window.no=obj.no; 14 window.no(); 15 alert(obj.val==true); 16 alert(window.val==true);

读书人网 >JavaScript

热点推荐