[英]Why can't I use 'this' when creating this javascript object literal?
[英]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.