簡體   English   中英

Javascript:為什么不能對象文字使用賦值?

[英]Javascript: Why can't object literal use assign?

在Javascript中,Object具有assign函數。 由於對象文字具有__proto__Object.prototype ,為什么對象文字不能使用assign並且必須直接通過Object?

Object.assign({}, {hello: 'world'})

const o = {};
o.assign({add: 'more stuff'})

Object原型沒有assign方法。 打開F12控制台並鍵入Object.prototype以查看基礎對象原型上的可用內容。

Object.assign被認為是靜態方法,而不是實例方法。

這是因為assign是一種靜態函數。 它未定義到原型中。

這是一個例子:

 function SomeClass(foo) { this.foo = foo; } // this is a method, it is attached to the prototype SomeClass.prototype.showFoo = function() { console.log(this.foo); } // this is a static method, it is not attached to the prototype SomeClass.bar = function() { console.log("bar"); } var instance = new SomeClass("foo"); console.log(instance.showFoo); // OK console.log(instance.bar); // not OK console.log(SomeClass.showFoo); // not OK console.log(SomeClass.bar); // OK 

assign函數不在Object的prototype屬性中,只有在其上定義的屬性和方法可以被創建的對象訪問,以證明我們這樣做:

Object.prototype.assign = function(){}; // this create a function called assign in the prototype property of Object
var obj = {};
obj.assign(); // Now we can access the assign function with the object literal

希望這有幫助。

暫無
暫無

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

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