JavaScript链式方法Delimma [英] JavaScript Chainable Method Delimma

查看:71
本文介绍了JavaScript链式方法Delimma的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2种方法想用作可链接方法.可以使用其他方法来进一步修改文本.

I have 2 methods that I'd like to use as chainable methods. Other methods may be chained to further modify text.

从左返回X个字符. 从右返回X个字符.

left returns X characters from the left. right returns X characters from the right.

目前,我可以这样做:

var txt = "hello";
S$(txt).left(4).right(2).val //returns "ll"

我想做的就是这个. 基本上,我想在最后一个链接方法之后返回结果,而不必调用该属性.这可能吗?

What I want to do is this. Basically I want to return the results after the last chained method without having to call the property. Is this possible?

var txt = "hello";
S$(txt).left(4).right(2) //returns "ll"

下面是主要代码:

(function (global) {
    
    var jInit = function(text){
        this.text = text;
        this.val = text;
    }
    
    var jIn = function(text){
        return new jInit(text);
    }
    
    var jStringy = jStringy || jIn;
    
    
    jInit.prototype.left = function (num_char) {
        if (num_char == undefined) {
            throw "Number of characters is required!";
        }
        this.val = this.val.substring(0, num_char);
        return this;
    }
    
    jInit.prototype.right = function (numchar) {
        this.val = this.val.substring(this.val.length - numchar, this.val.length);
        return this;
    }

    global.jStringy = global.S$ = jStringy;
    
    return this;

}(window));

推荐答案

您可以覆盖 ObjectvalueOftoString方法对其进行归档.

You can override valueOf and toString methods of Object to archieve it.

示例:

var myObject = {
    value: 5,
    valueOf: function(){
        return this.value;
    },
    toString: function() {
        return 'value of this object is' + this.value;
    }
};

由于Javascript是鸭子输入语言,因此没有什么会阻止您执行数学式操作字符串连接原始值/对象的操作,因为这些方法在表达式求值过程中都会被调用,无论它们来自何处.

As Javascript is a duck typing language, nothing will prevent you from performing mathematical operations and string concatenation against primitive values/objects as these methods are called during expression evaluation process no matter where they came from.

示例:

console.log(myObject + 10); 将打印15

alert(myObject); 将打印此对象的值为5"

alert(myObject); will print 'value of this object is 5'

这篇关于JavaScript链式方法Delimma的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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