在javascript中,如何定义常量函数?

在javascript中,如何定义常量函数?,javascript,Javascript,我在chrome扩展中遇到了一些问题,无法编辑页面中的一个函数,以便按照我的意愿进行操作。我想在文档加载开始时创建一个函数名。然后,页面中的exist脚本无法创建具有该名称的新函数,因此必须在加载文档时使用my first函数 因此,我想设置一个CONST函数,该函数不能由页面的所有其他脚本再次设置 有没有办法做到这一点 例如: function unchangeable(){ alert() } //some code expanding ........, and new function

我在chrome扩展中遇到了一些问题,无法编辑页面中的一个函数,以便按照我的意愿进行操作。我想在文档加载开始时创建一个函数名。然后,页面中的exist脚本无法创建具有该名称的新函数,因此必须在加载文档时使用my first函数

因此,我想设置一个CONST函数,该函数不能由页面的所有其他脚本再次设置

有没有办法做到这一点

例如:

function unchangeable(){
 alert()
}
//some code expanding ........, and new function name unchangeable() can not be set again
function unchangeable(){ ....
 ..........
}
//this new function will fire an error, and when we call unchangeable() from now, he still create an alert()
或者在他第一次调用函数之前,是否有任何方法可以编辑函数?

您可能可以使用它。您应该能够将
可写
(和
可配置
,我认为)设置为false,以使函数按您想要的方式运行

Object.defineProperty(window, 'unchangeable', {
    value: function(){
         alert();
    },
    enumerable: true,
    writable: false,
    configurable: false
});

根据您的chrome版本,
const unchangeable=function(){…}
应该可以正常工作感谢Rocket Hazmat,
writeable:false
是最好的!!在
defindProperty
的文档中,我看到
Object.defineProperty(o,'a',{value:1})
等于
{writeable:false,configurable:false,enumerable:false}