js中的一些函式問題

2021-10-02 19:37:38 字數 3703 閱讀 3988

test1

function

foo(

)return

this;}

vargetname

=function()

foo().

getname()

;//1

解析:

宣告提前後再分析**。

var getname;

function

foo(

)return

this;}

getname

=function()

foo().

getname()

;

foo( )返回的是指向window的this

this.getnam( )查詢的是window中屬性為getname的函式

getname在foo( )時被重新設定,故輸出為1。

test2

var

getname

=function()

function

getname()

getname()

;// 4

解析:函式宣告提前後再分析

var getname;

function

getname()

getname

=function()

getname()

;

將函式宣告提前,function宣告也提前了,相同名字的直接覆蓋,故輸出4。

test3

function

foo(

)this.a

=function()

a=function()

vara

=function()

} foo.prototype.a=

function()

foo.a=

function()

foo.a(

);//6var obj =

newfoo()

; obj.a(

);//2 foo.a(

);//1

將**進行改寫

function

foo(

)this.a

=function()

} foo.prototype.a=

function()

foo.a=

function()

foo.a(

);var obj =

newfoo()

; obj.a(

);foo.a(

);

第一次foo.a()呼叫的外層函式,輸出為6;

foo例項化建立obj,例項化優先呼叫this.a,故輸出為2;

再呼叫foo.a()時為1;

test4

var name =

'lili'

;var obj =

} console.

log(obj.prop.

getname()

);//輸出 ivan 此時this指向了prop裡存放的物件

var test = obj.prop.getname;

console.

log(

test()

);//輸出 lili 此時this指向了全域性物件window

}

test5

var day =

"valentine's day"

;var object =}}

alert

(object.

getday()

());

// valentine's day

object.getday( )返回的是乙個函式

函式執行,this指向window,所以返回的是valentine』s day;

tset6

var i =10;

function

test()

console.

log(

this

.i);

// 10

console.

log(i)

;//6

}test()

;console.

log(i)

;//10

解析:

1、由於給區域性變數i賦值,所以輸出為20

2、for迴圈輸出0、1、2、3、4、5,當i = 6終止迴圈

3、再一般函式中使用this指代全域性物件,故輸出為10;

4、for迴圈結束後,i=6 ,故輸出為6

5、輸出全域性變數 i= 10;

test7

var user =

} console.

log(user.

getcount()

);//1var res = user.getcount;

console.

log(

res())

;// undefined

解析:

getcount函式被user物件呼叫 ,this指向user

res 變數接收的是函式體

res執行時 this指向window window 中沒有count 所以返回undefined

test8

for

(var i =

0; i <

4; i++),

1000);

}

js首先執行主線程,非同步相關的會儲存在非同步佇列

主線程執行後 i = 4;

test9

var test =

(function

(a)})(

function

(a,b)(1

,2))

; console.

log(

test(4

));//5

// 立即執行函式傳參

// 先傳參 1 ,2 return a = 1 ;

// a = this.a = 1;

// 傳入 test(4) b = 4

// return this.a + b = 1 + 4

test10

function

fun(a))(

);

console.

log(b)

;//undefined

varb

=function()

console.

log(b)

;//fun

}fun(1

);// 解析:

// ao

// ao

// ao

一些js技巧函式

1 將類陣列物件轉為陣列物件 slice.call arguments 2 void 0 undefined 3 型別判斷 object.prototype.tostring.call object array 4 陣列遍歷賦值可通過如下方法 var a 1,2,3,4 len a.length,b...

JS一些工具函式

資料型別對照列表 var typelist 判斷資料型別,返回字串 function type obj 是普通物件,且不為空,返回布林值 function objectisnotempty obj 該方法只針對普通 物件和陣列進行深度拷貝。function deepcopy obj 物件和陣列 if...

js中的一些方法

陣列 map 方法建立乙個新陣列,其結果是該陣列中的每個元素都呼叫乙個提供的函式後返回的結果。返回值 乙個新陣列,每個元素都是 函式的結果。var array1 1,4,9,16 const map1 array1.map x x 2 console.log map1 expected output...