簡體   English   中英

使用Typescript進行屬性名稱沖突

[英]property name collision using Typescript

我遇到了與功能對象( Function.name )上的保留屬性發生沖突的問題,我想知道下面是否有辦法在我的“ home”類上有一個名為“ 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
*/

打字稿文件:

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屬性是只讀的。 無法輸入新值,因為該值的描述符阻止了該值。 我建議您為財產選擇另一個名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM