Is there a way to tell if a function in JavaScript is getting over written?

一个人想着一个人 提交于 2019-12-10 18:22:18

问题


Is there a way to tell if a function I've written is getting overwritten or redefined? For example, say a guy named Jack has the function below:

// Jack's function on team 1
function doSomething() {
    // doing things
}

and one day he finds out that a teammate in the north pole of planet Zaxxon has used the same function name:

// Zaxar's function on team 2
function doSomething() {
    // doing something else
}

As you can see Zaxar and Jack are using the same function name. Neither Zaxar nor John discovered the problem until 6 months into the project. They know they can put an alert in their function and check it at runtime but let's say Zaxar and Jack both have 2 trillion functions and they are using 1 million JavaScript libraries and they realize it's impractical to put alerts in each function.

Is there a way to help Zaxar and Jack discover if there are any name collisions at runtime? Or is there a setting that will tell the JavaScript engine to throw errors on name collisions?

More information
I'm loading in a few libraries and I think that one of them is using the same function name as me. So in this example, there really isn't another developer I can correlate with. It's finding out if the library(s) that I load in are using the same function names and preventing something like this from happening down the line.


回答1:


Although the suggestion on namespacing is apt, you may also be interested in the writable and configurable properties of Object.defineProperty descriptors if you wanted to prevent overwriting of specific functions:

Object.defineProperty(window, "myUnchangeableFunction", {value: function () {
    alert("Can't change me");
}, writable: false, configurable: false});

/*
function myUnchangeableFunction () { // TypeError: can't redefine non-configurable property 'myUnchangeableFunction'
    alert('change?');
}

var myUnchangeableFunction = function () { // TypeError: can't redefine non-configurable property 'myUnchangeableFunction'
    alert('change?');
};
*/

myUnchangeableFunction();

You should check support in the browsers you wish to support, however, as some older browsers might not support this functionality.



来源:https://stackoverflow.com/questions/19354090/is-there-a-way-to-tell-if-a-function-in-javascript-is-getting-over-written

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!