JS函數調用的方法

來源:互聯網
上載者:User

標籤:style   blog   io   strong   ar   cti   new   log   

JS函數調用的四種方法:方法調用模式,函數調用模式,構造器調用模式,apply,call調用模式

1.方法調用模式:
先定義一個對象,然後在對象的屬性中定義方法,通過myobject.property來執行方法,this即指當前的myobject
對象。
var blogInfo={
  blogId:123,
  blogName:"werwr",
  showBlog:function(){alert(this.blogId);}
};

blogInfo.showBlog();

2.函數調用模式
定義一個函數,設定一個變數名儲存函數,this綁定到window對象。

var myfunc = function(a,b){
  return a+b;
}

alert(myfunc(3,4));

3.構造器調用模式
定義一個函數對象,在對象中定義屬性,在其原型對象中定義方法。執行個體化該對象,並調用其方法。
var myfunc = function(a){
  this.a = a;
};
myfunc.prototype = {
  show:function(){alert(this.a);}
}

var newfunc = new myfunc("123123123");
newfunc.show();

4.apply,call調用模式
var myobject={};
var sum = function(a,b){
  return a+b;
};
var sum2 = sum.call(myobject,10,30); //var sum2 = sum.apply(myobject,[10,30]);
alert(sum2);

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.