js方法的写法

Posted on 2021-07-23 06:31  猫头唔食鱼  阅读(1736)  评论(0编辑  收藏  举报

写法1:最常用的写法

function test() {}

写法2:变量的形式

let a = () => {}

写法3:对象收编变量

 let obj = {
         test() {}
     }

写法4:对象收编变量——链式调用

let obj = {
         test() {
             return this
         },
         test2() {
             return this
         }
     }
     // 链式调用
     obj.test().test2()

写法5:function也是对象的一种

  let Obj = function () {}
  Obj.test = function () {}
  Obj.test()

写法6:function里return一个函数

   function Obj() {
         return {
             test() {}
         }
     }
     let o = new Obj()
     o.test()

写法7:挂载原型链

 let Fn = function () {}
     Fn.prototype.test = function () {
         console.log(1111);
     }
     let o = new Fn()
     o.test()

写法8:挂载原型链的另一种形式

  let Fn = function () {}
     Fn.prototype = {
         test() {}
     }
     let f = new Fn()
     f.test()

写法9:挂载原型链——链式调用

let Obj = function () {}
     Obj.prototype.test = function () {
         return this
     }
     Obj.prototype.test2 = function () {
         return this
     }
     let fn = new Obj()
     fn.test().test2()

写法10:挂载原型链——链式调用的另一种方式

 let Obj = function () {}
     Obj.prototype = {
         test() {
             return this
         },
         test2() {
             return this
         }
     }
     let fn = new Obj()
     fn.test().test2()

写法11:挂载Function类(不传参的)

Function.prototype.test = function () {
         console.log(333)
     }

     // 两种调用方式
     let f = function () {}
     f.test()

     let fn = new Function()
     fn.test()

写法12:挂载Function类(传参的)

  Function.prototype.addMethod = function (name, fn) {
         this[name] = fn //  这里是this[name] = fn
     }
     // 调用方式1
     var o = function () {}
     o.addMethod('test', function () {
         console.log(2);
     })
     o.test()

     // 调用方式2
     var p = new Function()
     p.addMethod('test2', function () {
         console.log(3);
     })
     p.test2()

写法13:挂载Function——链式调用

 Function.prototype.addMethod = function (name, fn) {
         this[name] = fn
         return this
     }

     var x = new Function()
     x.addMethod('test', function () {
         console.log(4);
         return this
     })
     x.addMethod('test2', function () {
         console.log(5);
         return this
     })
     x.test().test2()

     let y = function () {}
     y.addMethod('test3', function () {
         console.log(6);
         return this
     })
     y.addMethod('test4', function () {
         console.log(7);
         return this
     })
     y.test3().test4()

写法14:终极写法(链式添加方法和链式调用方法)

 Function.prototype.addMethod = function (name, fn) {
         this.prototype[name] = fn
         return this
     }
     var Methods = function () {}
     Methods.addMethod('test', function () {
         console.log('last');
         return this
     }).addMethod('test2', function () {
         console.log('last2');
         return this
     })
     // 只有这种调用方法
     var x = new Methods()
     x.test().test2()