1 构造函数
在 JavaScript 里,构造函数用于创建对象。首字母大写,是一个很好地习惯。
// 构造函数
const Phone = function (model, brand){
this.model = model,
this.brand = brand
}
phone.prototype.clickPicture = function(){
console.log(`${
this.brand} ${
this.model} clicks picture!`)
}
// 使用 new 关键字创建对象
const iphone = new Phone("Iphone 12", "Apple")
console.log(iphone.clickPicture())
1.1 内置的构造函数
如下代码:
let a = new Object(); // A new Object object
let b = new String(); // A new String object
let c = new Number(); // A new Number object
let d = new Boolean(); // A new Boolean object
上面这些都是内置构造函数。
2 如何创建类
JavaScript 里,创建对象模板的另一种方法,就是类。它有自己的构造函数用于初始化属性变量。
2.1 类的构造函数特征
- 需要提供确切地函数名称
- 创建对象时,自动执行
- 初始化对象属性
- 如果不定义构造函数,JavaScript 将提供默认的构造方法
- 使用
new
关键字创建新对象
举个例子
class Phone{
constructor(model, brand){
this.model = model
this.brand = brand
}
// 我们不应该在构造函数里,调用 clickPicture 方法
clickPicture() {
console.log(`${
this.brand} ${
this.model} clicks picture!`)
}
}
// iphone 是类实例
const iphone = new Phone("Iphone 12", "Apple")
console.log(iphone.brand)
console.log(iphone.clickPicture())
注意:JavaScript 的类仅仅是语法糖,底层是靠原型实现的。
2.2 类的继承
继承允许从父类获取功能,一个类可以继承父类的所有方法和属性。
举个例子
class Phone{
constructor(model, brand){
this.model = model
this.brand = brand
}
clickPicture() {
console.log(`${
this.brand} ${
this.model} clicks picture!`)
}
}
class Iphone extends Phone {
constructor(model, brand, software){
super(model, brand)
this.software = software
}
}
const tenPro = new Iphone("10 pro", "Apple", "IOS")
console.log(tenPro)
3 new 关键字
new 关键字允许用户创建自定义的对象类型。比如
function Car(make, model, year, owner) {
this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
}
...
var car1 = new Car('Eagle', 'Talon TSi', 1993, rand);
var car2 = new Car('Nissan', '300ZX', 1992, ken);