只有在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 :(得分:0)
第一种情况是创建" class"而且你可以制作任意数量的物品。
在第二种和第三种情况下,您自己创建了对象,而您无法从对象创建对象。您可以在创建后立即使用它们:
// 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