JavaScript函數及其prototype

來源:互聯網
上載者:User

JavaScript函數及其prototype
一、定義函數可以通過聲明定義,也可以是一個運算式。
(1)函式宣告式:
分號是用來分隔可執行JavaScript語句,由於函式宣告不是一個可執行語句,所以不以分號結束。

function a(){  console.log('bbb');}
(2)函數運算式:
函數運算式以分號結尾,因為它是一個執行語句。
var a = function(){  console.log('aaa');}
(3)聲明式變體:
var a = function a(){  console.log('bbb');}
完全等價於 function b(){}
二、函數執行JavaScript解析器將當前範圍內聲明的所有變數和函數都會放到範圍的開始處,但是,只有變數的聲明被提前到範圍的開始處了,而賦值操作被保留在原處。
樣本1:
var a = function(){  console.log('aaa');}function a(){  console.log('bbb');}a();//結果:aaa
樣本2:
(function() {  console.log(noSuchVariable);})();//報錯,因為noSuchVariable變數根本沒定義


(function() {console.log(declaredLater);//"undefined"var declaredLater = "Now it's defined!";console.log(declaredLater);//"Now it's defined!"})();//上面這段代碼是正確的,沒有任何問題。

樣本3:

var a;         // 聲明一個變數,標識符為afunction a() {} // 聲明一個函數,標示符也為aalert(typeof a);  // functionfunction a() {}var a;alert(typeof a);  //functionfunction a() {}var a = 1;alert(typeof a);  //numbervar a = 1;function a() {}alert(typeof a);  //number
總結:
變數的聲明被提前到範圍頂部,賦值保留在原地;
聲明式函數整個“被提前”;
函數運算式只有變數“被提前”了,函數沒有“被提前”;
同名情況下,變數先“被提前”,函數再“再被提前”(即函數覆蓋變數)
賦值會根據前後順序進行覆蓋!
三、函數是對象[typeof instanceof]在 JavaScript 中使用 typeof 操作符判斷函數類型將返回"function"。但JavaScript函數描述為一個對象更加準確。JavaScript函數有屬性和方法。
(1)typeof區分對象和其他原始值
JavaScript的資料類型分為:原始類型(數字、字串、布爾值、null、undefined)和物件類型。
typeof[任何類型]傳回值(boolean、string、number、object、undefined)和 function
typeof 2;     //'number'typeof '2';   //'string'typeof true;  //'boolean'typeof [];    //'object'typeof null;  //'object'typeof undefined; //'undefined'var a = function(){}; typeof a; //'function'
對於所有內建可執行對象,typeof一律返回“function”
typeof new Number(2);     //'object'typeof new String('2');   //'object'typeof new Boolean(true); //'object'
(2)instanceof[對象 instanceof 類]判斷一個對象是否為類的執行個體
[] instanceof Object; //true2 instanceof Number; //falsenew Number(2) instanceof Number; //true
樣本:
var a = function(){};var b = function(){};a.prototype = new b();new a() instanceof b; //truenew a() instanceof Object; //true
首先確定b.prototype,如果b.prototype在a對象的原型鏈中,返回true,否則返回false。
注意;所有對象都是Object的執行個體。
(3)擴充 Object.prototype.toString.call([]) === '[object Array]';
四、prototypeJavaScript 對象有兩種不同的屬性,一種是對象自身的屬性,另外一種是繼承於原型鏈上的屬性。
JavaScript中,類的所有執行個體對象都從同一個原型對象上繼承屬性,因此,原型對象是類的核心。
(1)只有函數有prototype,對象沒有
var b = {};b.prototype.bbb='bbb';  //報錯b.prototype為undefinedfunction b(){}   b.prototype.bbb='bbb';console.log(b);            //結果:function b(){}console.log(b.prototype);  //結果:b {bbb: "bbb"}console.log(b.bbb);        //結果:undefinedconsole.log(new b().bbb);  //結果:bbb
(2)prototype是函數的內建屬性(用於設定函數的原型),__proto__是對象的內建屬性(用於設定對象的原型)。
PS:注意區分函數和對象
function test(){}test.prototype;   //結果:test {}new test().prototype;   //結果:undefined,對象沒有prototypenew test().__proto__;   //結果:test {}   function a(){     this.v='vvv';}a.prototype; //a {}new a.__proto__; //a {}new a().__proto__ === a.prototype;  //true 執行個體對象的__proto__,指向函數的原型
(3)每個JavasScript函數都自動擁有一個prototype屬性。這個屬性的值是一個對象,這個對象包含唯一一個不可枚舉屬性constructor。constructor屬性的值是一個函數對象。
function a(){     this.v='vvv';}a.prototype.constructor === a; //true[物理地址一樣]a.prototype.constructor; //constructor屬性指代這個類a.prototype.constructor.__proto__ === a.__proto__ === Function.prototype; //true Object.prototype.constructor.__proto__ === Object.__proto__ === Function.prototype; //true
PS:所有構造器、函數的__proto__都指向Function.prototype,它是一個空函數(Empty function)
(4)執行個體
樣本1:
function a(){}function b(){}a.prototype = {aaa:'aaa'};b.prototype = a.prototype;var aa1 = new a();var bb1 = new b();//aa1.prototype.aaa='xxx';   //錯誤,對象沒有原型a.prototype.aaa = 'xxx';console.log( aa1.aaa );    //xxxconsole.log( bb1.aaa );    //xxx
補充:a===b; //false a.prototype === b.prototype; //true

執行個體2:
function a(){}function b(){ this.bbb='bbb'}a.prototype = new b();  //相當於a.prototype = {bbb: "bbb"};console.log(new a().bbb ); //結果:bbb
補充:a.prototype === b.prototype; //false
五、執行個體方法&靜態方法(1)執行個體方法
function a(){}a.prototype.count = 0;var a1 = new a();a1.count++;var a2 = new a();a2.count++;a.prototype.count;  //0
PS:方法類似 a.prototype.method = function(){}
(2)靜態方法
function a(){}a.count = 0;new a().count();  //undefined,只能使用a.count調用
PS:方法類似 a.method = function(){}
(3)當代碼var p = new Person()執行時,new 做了如下幾件事情:
A. 建立一個空白對象
B. 建立一個指向Person.prototype的指標
C. 將這個對象通過this關鍵字傳遞到建構函式中並執行建構函式
六、閉包函數定義時的範圍鏈到函數執行時依然有效。
樣本-典型閉包:
var scope = "global scope";function checkScope(){  var scope = "local scope";  function f(){    return scope;  }    return f();}checkScope(); //local scope
樣本:更為常用的閉包
function counter(){  var n=0;  return{    count:function(){      return ++n;    },    reset:function(){      n=0;    }  };}var c1 = new counter();c1.count(); //1var c2 = new counter();c2.count(); //1c1.reset(); //c1置為0,c2不受影響c2.count(); //2
PS:執行個體對象互相不影響,單個執行個體對象內的方法,共用私人變數。
七、通過調用方法的形式來間接調用函數:apply&call
function a(){  console.log(this.x+this.y);}a.call({x:100,y:100});  //200function C(){  this.m = function(){    console.log(this.x+this.y);   }}var c = new C();c.m.call({x:100,y:100});  //200
call&apply第一個實參是要調用函數的母對象,會變為this的值。
函數.call(對象,參數1,參數2);
函數.apply(對象,[參數1,參數2]); //數組形式
補充:
function a(a,b,c,d){
//將偽數組轉變為真數組
var args = [].slice.call(arguments);
}
八、函數中this
function a(){  console.log(this);  //a {}   function b(){    console.log(this);  //window  }  b();}new a();
特別注意:函數內建函式this指向window
此問題在strict 模式已被修改;在非strict 模式中,可使用變數接收外部函數this供內建函式使用,如var that = this;
九、回調(函數當參數)function a(callback){
callback();
}
a(function(){
console.log('aaa');
});
更加靈活,首頁面只需為子頁面提供對應介面,具體處理邏輯全部由子頁面處理。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.