簡體   English   中英

Javascript-在基元上獲取和設置屬性會隱式創建對象包裝器

[英]Javascript - Getting and setting properties on primitives implicitly creates object wrappers

我正在讀一本書,名為《 有效的JavaScript:利用JavaScript的力量的68種特定方法》 ,第4點更喜歡基元而不是對象包裝,並且碰到了這句話。

在基元上獲取和設置屬性會隱式創建對象包裝器

這會創建對象包裝嗎?

"hello".someProperty = 17;

編輯

如果以上語句創建了一個對象,請解釋此行為。

var test = "foo";
test.bar = "new prop";
test.bar //this prints undefined.
"hello".someProperty = 17;

上面的語句確實創建了一個對象包裝器,但是一旦完成任務就將其丟棄。

 var hello = 'Hello'; hello.someProperty = 17; console.log(hello.someProperty); 

這就解釋了為什么嘗試為基元分配屬性不起作用,但也不會引發錯誤。 屬性分配成功,但是該屬性設置在包裝對象上,該包裝對象立即被銷毀。 因此,當您以后去查找物業時,就再也沒有了。

在內部, this基本類型是object

 String.prototype.thisType = function () { return typeof this; }; var hello = "hello"; console.log(typeof hello); console.log(hello.thisType()); 

在這里閱讀更多

是的,它創建一個中間對象,使用后將其丟棄。 所以聲明

"hello".someProperty = 17;

將在內部這樣執行:

var temp = new String("hello");  // or any other variable name
temp.someProperty = 17;

因此,現在無法訪問temp (或由JavaScript創建的任何命名變量),因為temp會立即創建並丟棄。

您必須使用新的關鍵字創建String對象。

var str = new String("My String");
//Here str is looks like
//String {"My String"}
str .xyz=5
str 
//now String {"My String", xyz: 5}

暫無
暫無

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

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