How do I create a basic JavaScript extension method which outputs the string 'Hello World'?

2

Not sure if the word 'extension method' is appropriate or not. I want to extend the JavaScript language to allow me to call .helloWorld() on any object and it will always return the string 'Hello World'.

I have tried ...

Object.prototype.helloWorld = function () {
    return "Hello World";
}

... but this is causing problems with many other object types. I keep getting jQuery error...

Unhandled exception at line 3869, column 3 in http://workflow/Scripts/jquery-3.2.1.js

0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'splice'

Is it possible to extend the base class JavaScript object so that a custom method is available regardless of the type of object? I have seen documentation on prototype but not sure if this is even the correct venue. I have seen jQuery extend() but this seems jQuery specific. I have seen discussions on extending methods vs. custom properties. I am left confused.

javascript
asked on Stack Overflow Jan 11, 2018 by barrypicker

2 Answers

4

Yes, it is possible, and you can do it with just a user script.

Extending the built-in JavaScript prototypes with non-standard properties and methods is generally considered a bad practice though, as it can often lead to unexpected behavior in code that didn't expect them.

If you do go there though, you can minimize the impact by making the property non-enumerable. That way code that iterates over an object's properties won't enumerate the property from the prototype chain.

Object.defineProperty(Object.prototype, 'helloWorld', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function () {
        return "Hello World";
    }
});
answered on Stack Overflow Jan 11, 2018 by Alexander O'Mara
1

Like said above use Object.defineProperty() method as the previous method Object.prototype._ definegetter _ has been deprecated in favor of the defineProperty method

answered on Stack Overflow Jan 11, 2018 by Ezekiel

User contributions licensed under CC BY-SA 3.0