簡體   English   中英

為什么我不能設置 JavaScript 函數的名稱屬性?

[英]Why can't I set a JavaScript function's name property?

我正在學習 JavaScript 並讀到函數就像對象,可以像這樣設置屬性:

var person = function(){
}
person.name="John Smith"; //output ""
person.age=21; //output 21
person.profession="Web Developer"; //output "Web Developer"

為什么名稱屬性為空?

謝謝

因為name函數對象的非標准, 不可寫 屬性 函數聲明和命名函數表達式命名 ,而您有一個name ""的匿名函數表達式。

你可能想要一個普通的對象:

var person = {
    name: "John Smith",
    age: 21,
    profession: "Web Developer"
};

name是一個特殊屬性,因為它在定義時給出了函數的名稱:

function abc(){

}

在這種情況下,name將返回字符串"abc" 此名稱無法更改。 在您的情況下,該函數沒有名稱,因此為空字符串。

http://jsfiddle.net/8xM7G/1/

您可能想要使用Prototype(請參閱JavaScript .prototype如何工作? )或簡單地將'person'轉換為哈希,如下所示:

var person = {};
person.name="John Smith"; //output "John Smith"
person.age=21; //output 21
person.profession="Web Developer"; //output "Web Developer"

name屬性由Function構造函數設置,不能直接覆蓋。 如果函數聲明為匿名,則將其設置為空字符串。

例如:

var test = function test() {};
alert(test.name); // Displays "test"
test.name = "test2";
alert(test.name); // Still displays "test"

可以更改名稱屬性!

Function.name屬性可在MDN上詳細 configurable

由於它是可配置的,我們可以改變它的writable屬性,以便可以更改它。 我們需要使用defineProperty來執行此操作:

var fn = function(){};
Object.defineProperty(fn, "name", {writable:true});
// now you can treat it like a normal property:
fn.name = "hello";
console.log(fn.name); // outputs "hello"

您可以使用Object.defineProperty更改屬性的value (即使不觸及其writeable標志):

 function fn () {} console.log(fn.name) // Outputs fn Object.defineProperty(fn, 'name', { value: 'newName' }) console.log(fn.name) // Outputs newName

暫無
暫無

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

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