gpt4 book ai didi

javascript - 使用 Typescript 的属性名称冲突

转载 作者:行者123 更新时间:2023-11-30 17:20:55 25 4
gpt4 key购买 nike

我遇到了一个我认为与函数对象 ( Function.name ) 上的保留属性发生冲突的问题,我想知道是否有办法在我的“家”上有一个名为“名称”的静态变量下面的类,全部小写,不与 Function.name 冲突?

原始 javascript:

// Note: I've changed the "home" class to "_c0" here to show the problem more clearly.
var myApi;
(function (myApi) {
var _c0 = (function () {
function _c0() { }
_c0.name = "Home"; // this is colliding with the "Function.name". there is no "name" property on this object during runtime
_c0.Name = "Home";
_c0.name1 = "Home";
_c0.url = "/Home";
return _c0;
})();
myApi.home = _c0;
})(myApi || (myApi = {}));

console.log(myApi.home.name); // prints "_c0" <- this is the name of the function
console.log(myApi.home.Name); // prints "Home"
console.log(myApi.home.name1); // prints "Home"
console.log(myApi.home.url); // prints "/Home"

for(var prop in myApi.home)
console.log(prop + ": " + myApi.home[prop]);
/* prints: (note the lack of "name: Home" in the output)
Name: Home
name1: Home
url: /Home
*/

typescript 文件:

module myApi {
export class home {
static name = "Home";
static Name = "Home"; // just testing
static name1 = "Home"; // just testing
static url = "/Home";
}
}

console.log(myApi.home.name);
console.log(myApi.home.Name);
console.log(myApi.home.name1);
console.log(myApi.home.url);
for (var prop in myApi.home)
console.log(prop + ": " + myApi.home[prop]);

最佳答案

不,没有办法做到这一点。函数对象具有 name 属性并且不能被覆盖。可以在下面的代码片段中找到简单的证明:

var F = function(){}; 
Object.defineProperty(F, "name", {value: "Home"});
//TypeError: Cannot redefine property: name

这意味着静态 name 属性是只读的。无法输入新值,因为它被该值的描述符阻止。我建议您为您的属性(property)选择另一个名称。

关于javascript - 使用 Typescript 的属性名称冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25155275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com