JavaScript函式內部屬性
JavaScript函式內部屬性
函式內部有兩個特殊物件,this、arguments,其中arguments是一個類陣列物件,包含著傳入函式中的所有引數,主要用來儲存函式引數。arguments物件還有一個callee屬性,callee是一個指標,指向擁有這個arguments物件的函式。
callee
function fact(num){ if(num<=1){ return 1; }else{ return num*fact(num-1); } }
這是一個實現階乘的函式,採用遞迴的方式,這種方式存在一個問題就是,當fact的名稱更改以後,如果不及時更改函式內部的函式名稱,該函式則無效。此時採用callee屬性替代當前擁有num引數物件的函式也就是fact.
採用callee實現如下
function fact(num){ if(num<=1){ return 1; }else{ return num*arguments.callee(num-1); } }
this
this引用的是函式執行的環境物件,當函式被當做某個物件的方法呼叫時,此時的this物件引用的是當前呼叫函式的物件。
不同的環境this指向的值不同,下面是幾種this在不同執行環境下所指向的值
方法呼叫
當函式作為物件方法的時候,函式裡的this被繫結到當前物件上(也可以稱之為方法呼叫)
例如:
var myNum = { value:1, increment:function(arg){ this.value +=arg; } }; myNum.increment(3); console.log('example1:'+myNum.value);//example1:4
上述的increment是一個物件方法,該物件方法內部的this指向的就是當前物件
函式呼叫
當函式作為非物件方法時候,this繫結到全域性物件window,如果此時要呼叫內部函式可以採用that = this。
// 一般的函式 function add(a){ return a+2 ; } var value = 2; myNum.count = function (){ let value = 1; let help = function(){ this.value = add(this.value); } help(); console.log(this.value);//4 } myNum.count(); that = this方式 var value = 2; myNum.count = function (){ let value = 1; let that = this; let help = function(){ that.value = add(that.value); } help(); console.log(that.value);//3 } myNum.count();
建構函式
用new運算子呼叫建構函式,會先建立一個連線到建構函式的prototype(原型物件),再將this繫結到該物件
function Person(name){
this.name = name; } Person.prototype.sayName = function(){ return this.name; } var person1 = new Person('TOM'); console.log(person1.sayName());
apply\call\bind
繫結this到指定的環境物件
var people = { name:"LILY" } console.log(Person.prototype.sayName.apply(people)); console.log(Person.prototype.sayName.bind(people)()); console.log(Person.prototype.sayName.call(people));
call :方法呼叫一個具有給定this值的函式,以及提供的引數列表。
apply: 方法呼叫一個具有給定this值的函式,以及提供的引數(陣列或類陣列物件)。
bind :方法建立一個新的函式,呼叫時設定this關鍵字為提供的“值”。
ES6 箭頭函式
es6箭頭函式裡的this指向定義時所在的物件,不是執行的環境物件,就說明this在箭頭函式裡使用時是一個不變的值
function foo(){ setTimeout(()=>{ console.log('name:',this.name); },1000) } var name = "kiki"; foo.call({name:"didi"});//name:didi 箭頭函式裡this的值指向的是定義時所在的環境物件,es5中實現箭頭函式的方法:採用 that = this這種機制,實現this的繫結 以上是對函式的內部屬性的理解。