Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

javascript - Function that can return a value and also act as an object

This question seems hard to form so I will just provide an example of what I am trying to accomplish::

function test(word) {
    return word
}

function replaceWord(word) {
    return word
}
test('Hello').replaceWord('World')

So I want to be able to return "Hello" and if I want to, chain the replaceWord function.

Comparable to how jquery handles things like

$('#element').something('doit').somethingElse();

I feel like I am on the right track with

var test = function (word) {
    return word;
}
test.prototype = {
    replaceWord: function (word) {
        return word;
    }
}

But since I am returning the string, the chain will not work. What is the proper way I am supposed to doing this to be be able to have a function that can return a value [test('Hello')] and also can act as an object to modify data for value/s returned by the function [test('Hello').replaceWord('World')] leaving the value at 'World'?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It’s impossible to return a plain value (without a wrapper or extra properties) that’s chainable in that way. This is especially true for strings, as they’re primitives and can’t have their own properties. jQuery accomplishes this by making everything a wrapper, along the lines of:

function test(word) {
    this.word = word;
}

test.prototype.next = function (word) {
    this.word = word;
    return this;
};

// or, if next() shouldn’t modify its context

test.prototype.next = function (word) {
    return new test(word);
};

and then

test.prototype.get = function () {
    return this.word;
};

to unwrap the wrapper. You’d use it as:

new test('Hello').next('World').get();

To drop the new like jQuery,

function test(word) {
    if (!(this instanceof test)) {
        return new test(word);
    }

    this.word = word;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...