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
71 views
in Technique[技术] by (71.8m points)

How do I write an extension method in JavaScript?

I need to write a few extension methods in JS. I know just how to do this in C#. Example:

public static string SayHi(this Object name)
{
    return "Hi " + name + "!";
}

and then called by:

string firstName = "Bob";
string hi = firstName.SayHi();

How would I do something like this in JavaScript?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

JavaScript doesn't have an exact analogue for C#'s extension methods. JavaScript and C# are quite different languages.

The nearest similar thing is to modify the prototype object of all string objects: String.prototype. In general, best practice is not to modify the prototypes of built-in objects in library code meant to be combined with other code you don't control. (Doing it in an application where you control what other code is included in the application is okay.)

If you do modify the prototype of a built-in, it's best (by far) to make that a non-enumerable property by using Object.defineProperty (ES5+, so basically any modern JavaScript environment, and not IE81 or earlier). To match the enumerability, writability, and configurability of other string methods, it would look like this:

Object.defineProperty(String.prototype, "SayHi", {
    value: function SayHi() {
        return "Hi " + this + "!";
    },
    writable: true,
    configurable: true
});

(The default for enumerable is false.)

If you needed to support obsolete environments, then for String.prototype, specifically, you could probably get away with creating an enumerable property:

// Don't do this if you can use `Object.defineProperty`
String.prototype.SayHi = function SayHi() {
    return "Hi " + this + "!";
};

That's not a good idea, but you might get away with it. Never do that with Array.prototype or Object.prototype; creating enumerable properties on those is a Bad Thing?.

Details:

JavaScript is a prototypical language. That means that every object is backed by a prototype object. In JavaScript, that prototype is assigned in one of four ways:

  • By the constructor function for the object (e.g., new Foo creates an object with Foo.prototype as its prototype)
  • By the Object.create function added in ES5 (2009)
  • By the __proto__ accessor property (ES2015+, only on web browsers, existed in some environments before it was standardized) or Object.setPrototypeOf (ES2015+)
  • By the JavaScript engine when creating an object for a primitive because you're calling a method on it (this is sometimes called "promotion")

So in your example, since firstName is a string primitive, it gets promoted to a String instance whenever you call a method on it, and that String instance's prototype is String.prototype. So adding a property to String.prototype that references your SayHi function makes that function available on all String instances (and effectively on string primitives, because they get promoted).

Example:

Object.defineProperty(String.prototype, "SayHi", {
    value: function SayHi() {
        return "Hi " + this + "!";
    },
    writable: true,
    configurable: true
});

console.log("Charlie".SayHi());

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

...