javascript有哪些方法定义对象
- 对象字面量:
var obj = {};
原型是Object.prototype
- 构造函数:
var obj = new Object();
Object.create()
:var obj = Object.create(Object.prototype);
Object.create(null)
没有原型Object.create({...})
可指定原型
1. 字面量表示法(Literal Notation):
使用对象字面量 {}
直接创建对象,并在其中定义属性和方法。
const person = {
name: 'poetry',
age: 30,
sayHello: function() {
console.log('Hello!');
}
};
2. 构造函数(Constructor):
使用构造函数创建对象,可以定义一个构造函数,然后使用 new
关键字实例化对象。
function Person(name, age) {
this.name = name;
this.age = age;
this.sayHello = function() {
console.log('Hello!');
};
}
const person = new Person('poetry', 30);
3.Object.create()
方法:
使用Object.create()
方法创建一个新对象,并将指定的原型对象设置为新对象的原型。可以传入一个原型对象作为参数,也可以传入null
作为参数来创建没有原型的对象。
const personPrototype = {
sayHello: function() {
console.log('Hello!');
}
};
const person = Object.create(personPrototype);
person.name = 'poetry';
person.age = 30;
4.class
关键字(ES6引入):
使用 class
关键字可以定义类,并通过 new
关键字实例化对象。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log('Hello!');
}
}
const person = new Person('poetry', 30);
5. 工厂函数(Factory Function):
使用一个函数来封装创建对象的逻辑,并返回新创建的对象。
function createPerson(name, age) {
const person = {};
person.name = name;
person.age = age;
person.sayHello = function() {
console.log('Hello!');
};
return person;
}
const person = createPerson('poetry', 30);
6. 原型(Prototype):
在 JavaScript 中,每个对象都有一个原型(prototype),可以通过原型链来继承属性和方法。
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
console.log('Hello!');
};
const person = new Person('poetry', 30);
7.Object.assign()
方法:
使用 Object.assign()
方法可以将一个或多个源对象的属性复制到目标对象中,从而创建一个新对象。
const person1 = {
name: 'poetry',
age: 30
};
const person2 = {
sayHello: function() {
console.log('Hello!');
}
};
const person = Object.assign({}, person1, person2);
THE END
暂无评论内容