2016-12-30 108 views
-1

只有在javascript中創建對象的第一種方式是讓我從中創建新對象。第二和第三種創建對象的方式都會拋出錯誤 有人可以告訴我爲什麼會發生這種情況。並讓我知道我在代碼中犯了什麼錯誤。從其他創建新對象

'use strict' 

// First Way for creating object 
var log = function(){ 
    this.name = 'nitesh', 
    this.lastName = 'Yadav', 
    this.age = '21' 
} 
Object.defineProperty(log,'name',{ 
    enumerable: false, 
    writable: false, 
    configurable: false 
}) 
var for = new log(); ***// Works fine*** 
console.log(foo.name); // nitesh 

// Second Way for creating object 

var log2 = { 
    name: 'nitesh', 
    lastname: 'yadav', 
    age: '21' 
} 
var foo2 = new log2; ***//Not working*** 
console.log(foo2.name) // Result error Why??? 

// third Way for creating object 

var log3 = Object.create(Object.prototype,{ 
    name:{ 
     value: 'nitesh', 
     enumerable: true, 
     writable: true, 
     configurable: true 
    }, 
    age: { 
     value: '21', 
     enumerable: true, 
     writable: true, 
     configurable: true 
    } 
}) 

var foo3 = new log3; ***//Not working*** 
console.log(foo3.name) // Result error Why??? 
+0

var for = new log();會拋出異常,因爲'for'是保留字,不能用作變量名 – degr

+0

'Object.create' - 創建新對象,而不是類。你不能調用'new log3',因爲它不是一個類(也不是一個構造函數) – degr

+0

所有的命名都應該重做。從那開始吧! – mnemosdev

回答

0

第一種情況是創建「類」,並且可以根據需要製作任意數量的對象。

在第二種和第三種情況下,您正在創建對象本身,並且您無法從對象創建對象。您可以在創建後立即使用它們:

// Second Way for creating object 

var log2 = { 
    name: 'nitesh', 
    lastname: 'yadav', 
    age: '21' 
} 
// var foo2 = new log2; // This line is not needed 
console.log(log2.name) // No Error 

// third Way for creating object 

var log3 = Object.create(Object.prototype,{ 
    name:{ 
     value: 'nitesh', 
     enumerable: true, 
     writable: true, 
     configurable: true 
    }, 
    age: { 
     value: '21', 
     enumerable: true, 
     writable: true, 
     configurable: true 
    } 
}) 

//var foo3 = new log3; // This line is not needed 
console.log(foo3.log3) // No Error