使用函数构造对象通常是通过构造函数的方式。构造函数是一种特殊的函数,用于创建具有特定属性和方法的对象。
在JavaScript中,this
通常指向的是我们正在执行的函数本身,或者是指向该函数所属的对象(运行时)
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log("Hello, my name is " + this.name);
};
}
const person1 = new Person("Alice", 30);
person1.greet(); // 输出: Hello, my name is Alice
类是用于创建对象的模板。
ES6引入了类(Class)的概念,提供了一种更接近传统面向对象编程语言的语法来创建和管理对象。
我们使用 class 关键字来创建一个类,类体在一对大括号 {}
中,我们可以在大括号 {}
中定义类成员的位置,如方法或构造函数。
每个类中包含了一个特殊的方法 constructor()
,它是类的构造函数,这种方法用于创建和初始化一个由 class
创建的对象。
class ClassName {
constructor() { ... }
}
class WebSite {
constructor(name, url) {
this.name = name;
this.url = url;
}
}
定义好类后,我们就可以使用 new
关键字来创建对象:
class Student{
constructor(id,name){
this.id = id
this.name = name
}
}
var stu = new Student('1','tom')
console.log(stu)
类中可以使用static
关键字来生成类的静态成员
注意:类的静态成员只能使用类名来调用
class Student{
constructor(id,name){
this.id = id
this.name = name
}
static sayHello(){
console.log('hello')
}
}
var stu = new Student('1','tom')
console.log(stu)
Student.sayHello()
// 基类
class Animal {
// eat() 函数
// sleep() 函数
};
//派生类
class Dog extends Animal {
// bark() 函数
};
语法差异:
new
关键字。class
关键字定义,更接近其他面向对象编程语言的语法。原型链:
prototype
)属性添加方法,这样可以共享方法,节省内存。例如:Person.prototype.greet = function() {...}
。prototype
的方式是自动管理的,不需要手动设置,但可以通过静态方法或属性(使用static
关键字)来定义。继承:
Object.create()
或Person.prototype = Object.create(SuperPerson.prototype)
。extends
关键字。例如:class Student extends Person {}
。封装和复用:
#
前缀可以定义私有字段(在严格模式下)。例如:#name
。在 JavaScript 中,原型(prototype)是一个非常重要的概念,它为对象提供了继承和共享属性的机制。每个 JavaScript 对象都有一个与之关联的原型对象,通过原型对象,可以实现属性和方法的共享,从而减少内存占用。
所有的 JavaScript 对象都会从一个 prototype(原型对象)中继承属性和方法。
null
为止。每个 JavaScript 对象(除了 null)都自动拥有一个隐藏的属性 __proto__
,它指向该对象的原型对象。这个 __proto__
是实现继承的关键:
let obj = {};
console.log(obj.__proto__); // 输出: [object Object], 即 obj 的原型是 Object.prototype
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");