您现在的位置: 万盛学电脑网 >> 程序编程 >> 脚本专题 >> javascript >> 正文

javascript创建函数的20种方式汇总

作者:佚名    责任编辑:admin    更新时间:2022-06-22

       这篇文章主要介绍了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