我遇到了一个我认为与Function对象(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
*/
打字稿文件:
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]);
答案 0 :(得分:2)
没有办法做到这一点。函数对象具有name
属性,无法覆盖。可以在下面的代码段中找到简单的证据:
var F = function(){};
Object.defineProperty(F, "name", {value: "Home"});
//TypeError: Cannot redefine property: name
这意味着静态name
属性是只读的。无法输入新值,因为该值的描述符会阻止该值。我建议你为你的房产选择另一个名字。