如何链接功能而不使用原型? [英] How to chain functions without using prototype?

查看:88
本文介绍了如何链接功能而不使用原型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  function one(num){
返回num + 1;
}

函数two(num){
return num + 2;

$ / code>

我可以用两个(两个(5)))



但我更愿意使用(5).one()。two() .two()



如何在不使用原型的情况下实现此功能?

我尝试了解下划线链是如何工作的,但是他们的代码太过于激烈以至于无法理解它。解决方案

点语法是为对象保留的。所以你可以做一些像

 函数MyNumber(n){
var internal = Number(n);
this.one = function(){
internal + = 1;
//这里是允许链接的魔术:
返回这个;
}
// this.two analogous
this.valueOf = function(){
return internal;


$ b $ new MyNumber(5).one()。two()。two()。valueOf(); // 10

或者你要在原生Number对象的原型上实现这些方法/功能。这将允许(5).one()...


I have a bunch of useful functions that I have collected during my whole life.

function one(num){
    return num+1;
}

function two(num){
    return num+2;
}

I can call them with two(two(one(5)))

But I would prefer to use (5).one().two().two()

How can I achieve this without using prototype?

I tried to see how underscore chain works, but their code is too intense to understand it

解决方案

The dot syntax is reserved for objects. So you can do something like

function MyNumber(n) {
    var internal = Number(n);
    this.one = function() {
        internal += 1;
        // here comes the magic that allows chaining:
        return this;
    }
    // this.two analogous
    this.valueOf = function() {
        return internal;
    }
}

new MyNumber(5).one().two().two().valueOf(); // 10

Or you're going to implement these methods on the prototype of the native Number object/function. That would allow (5).one()...

这篇关于如何链接功能而不使用原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆