Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7520835
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T02:08:11+00:00 2026-05-30T02:08:11+00:00

I need to write a few extension methods in JS. I know just how

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T02:08:11+00:00Added an answer on May 30, 2026 at 2:08 am

    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. Add your function as a method to the prototype, and use this within the function to access the string it was called on. (Don’t use an arrow function, since you want this controlled by the caller, you don’t want to close over it.) 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 IE8¹ 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 Object.setPrototypeOf function (ES2015+) [or the deprecated __proto__ setter (ES2015+, optional, and only exists on objects that inherit [directly or indirectly] from Object.prototype), or
    • 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());

    There are some key differences between this and C# extension methods:

    • (As DougR pointed out in a comment) C#’s extension methods can be called on null references. If you have a string extension method, this code:

        string s = null;
        s.YourExtensionMethod();
      

      works (unless YourExtensionMethod throws when it receives null as the instance parameter). That isn’t true with JavaScript; null is its own type, and any property access on null throws an error. (And even if it didn’t, there’s no prototype to extend for the Null type.)

    • (As ChrisW pointed out in a comment) C#’s extension methods aren’t global. They’re only accessible if the namespace they’re defined in is used by the code using the extension method. (They’re really syntactic sugar for static calls, which is why they work on null.) That isn’t true in JavaScript: If you change the prototype of a built-in, that change is seen by all code in the entire realm you do that in (a realm is the global environment and its associated intrinsic objects, etc.). So if you do this in a web page, all code you load on that page sees the change. If you do this in a Node.js module, all code loaded in the same realm as that module will see the change. In both cases, that’s why you don’t do this in library code. (Web workers and Node.js worker threads are loaded in their own realm, so they have a different global environment and different intrinsics than the main thread. But that realm is still shared with any modules they load.)


    ¹ IE8 does have Object.defineProperty, but it only works on DOM objects, not JavaScript objects. String.prototype is a JavaScript object.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i need to write few applications about lowlevel videocard controling for my coursework. For
I need to write a java script. This is supposed to validate if the
I need to write an extension method on a byte[]. Is that possible?
I need to write a program or script that does a few things with
I need to write a few c header wrappers for a new programming language
I will need to write my own drivers for few controllers in my chipset.I
I need to write a few programs for a project I'm currently working on
I need write an update statement that used multiple tables to determine which rows
I need to write a program used internally where different users will have different
I need to write a Java Comparator class that compares Strings, however with one

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.