這篇文章主要介紹了javascript創建函數的20種方式匯總的相關資料,需要的朋友可以參考下
工作中常常會創建一個函數來解決一些需求問題,以下是個人在工作中總結出來的創建函數20種方式,你知道多少?
? 1 2 3 4 5 6 7 8 function sayHello(){ console.log('hello'); } function leave(){ console.log('goodbye'); } //test sayHello();為完成需求,趕緊聲明一個函數吧
? 1 2 3 4 5 6 7 8 9 var sayHello = function(){ console.log('hello'); } var leave = function(){ console.log('goodbye'); } //test leave();有求必應,函數表達數來解決
? 1 2 3 4 5 6 7 8 9 10 11 var Action = { sayHello : function(){ console.log('hello'); }, leave : function(){ console.log('goodbye'); } } //test Action.sayHello();創建一個方法對象類看起來更整潔
? 1 2 3 4 5 6 7 8 9 10 var Action = function(){}; Action.sayHello = function(){ console.log('hello'); } Action.leave = function(){ console.log('goodbye'); } //test Action.sayHello();為單體添加屬性方法,淨化命名空間
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 var Action = function(){ return { sayHello : function(){ console.log('hello'); }, leave : function(){ console.log('goodbye'); } } } // //test var a = Action(); a.leave();返回新對象我們還有更多的事情可以做
? 1 2 3 4 5 6 7 8 9 10 11 var Action = function(){}; Action.prototype.sayHello = function(){ console.log('hello'); } Action.prototype.leave = function(){ console.log('goodbye'); } //test var a = new Action(); a.sayHello();原型鏈指向防止創建多次
? 1 2 3 4 5 6 7 8 9 10 11 12 13 var Action = function(){}; Action.prototype = { sayHello : function(){ console.log('hello'); }, leave : function(){ console.log('goodbye'); } } //test var a = new Action(); a.leave();對象賦給原型看上去更整潔
? 1 2 3 4 5 6 7 8 9 10 11 12 var Action = function(){ this.sayHello = function(){ console.log('hello'); } this.leave = function(){ console.log('goodbye'); } } //test var a = new Action(); a.leave();別忘了還可以在類的內部添加屬性
? 1 2 3 4 5 6 7 8 9 10 Function.prototype.sayHello = function(){ console.log('hello'); } Function.prototype.leave = function(){ console.log('leave'); } //test var f = function(){}; f.sayHello();基類原型拓展,新的一片空間
? 1 2 3 4 5 6 7 8 9 10 11 12 13 Function.prototype.addMethod = function(name, fn){ this[name] = fn; } var methods = function(){}; methods.addMethod('sayHello', function(){ console.log('hello'); }); methods.addMethod('leave', function(){ console.log('leave'); }); //test methods.sayHello();通用定義方法函數使用更方便
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Function.prototype.addMethod = function(name, fn){ this.prototype[name] = fn; } var Methods = function(){}; Methods.addMethod('sayHello', function(){ console.log('hello'); }); Methods.addMethod('leave', function(){ console.log('leave'); }); //test var a = new Methods(); a.leave();原形賦值我們還可以用類操作
? 1 2 3 4 5 6 7 8 9 10 11 12