对象创建的方式
5种方法
-
对象字面量:使用花括号
{}
定义对象并初始化其属性和方法。例如:const obj = { name: 'John', age: 30, sayHi: function() { console.log('Hi!'); } };
-
构造函数:使用
new
关键字和构造函数创建一个新对象。例如:function Person(name, age) { this.name = name; this.age = age; this.sayHi = function() { console.log('Hi, my name is ' + this.name + ' and I am ' + this.age + ' years old.'); }; } const person = new Person('John', 30);
-
原型:使用构造函数的原型属性添加属性和方法。例如:
function Person(name, age) { this.name = name; this.age = age; } Person.prototype.sayHi = function() { console.log('Hi, my name is ' + this.name + ' and I am ' + this.age + ' years old.'); }; const person = new Person('John', 30);
-
Object.create():使用
Object.create()
方法创建一个新对象,该对象的原型指向传递的对象。例如:const person = Object.create({ sayHi: function() { console.log('Hi!'); } }); person.name = 'John'; person.age = 30;
-
**class:**使用
class
关键字定义一个类并创建对象。例如:class Person { constructor(name, age) { this.name = name; this.age = age; } sayHi() { console.log('Hi, my name is ' + this.name + ' and I am ' + this.age + ' years old.'); } } const person = new Person('John', 30);
#对象继承的方式
-
原型链继承:通过将子类的原型设置为父类的实例来实现继承。这样,子类就可以访问父类原型中的属性和方法。例如:Dog.prototype = new Animal();
function Animal(name) { this.name = name; } Animal.prototype.eat = function() { console.log('I am eating'); } function Dog(name) { this.name = name; } Dog.prototype = new Animal(); const dog = new Dog('Tom'); dog.eat(); // 'I am eating'
-
构造函数继承:通过在子类中调用父类构造函数来继承父类的属性和方法。例如:function Dog(name) { Animal.call(this, name);}
function Animal(name) { this.name = name; } Animal.prototype.eat = function() { console.log('I am eating'); } function Dog(name) { Animal.call(this, name); } const dog = new Dog('Tom');
-
组合继承:将原型链继承和构造函数继承结合起来使用,既继承了父类的属性和方法,也避免了原型链继承的缺点。例如:
function Animal(name) { this.name = name; } Animal.prototype.eat = function() { console.log('I am eating'); } function Dog(name) { Animal.call(this, name); } Dog.prototype = new Animal(); Dog.prototype.constructor = Dog; const dog = new Dog('Tom'); dog.eat(); // 'I am eating'
-
ES6 的 class 继承:通过使用
extends
关键字和super()
方法来继承父类的属性和方法。例如:class Animal { constructor(name) { this.name = name; } eat() { console.log('I am eating'); } } class Dog extends Animal { constructor(name) { super(name); } } const dog = new Dog('Tom'); dog.eat(); // 'I am eating'