先来看一个普通的构造函数
function Foo(name) {
this.name = name;
this.sayName = function() {
return '不是原型上的方法';
}
}
let bar = new Foo();
console.log(bar.sayName()) // 不是原型上的方法
function Foo(name) {
this.name = name;
}
Foo.prototype.sayName = function() {
return '是原型上的方法';
}
let bar = new Foo('007');
console.log(bar.sayName()) // 是原型上的方法
下面使用class的语法来重写这个例子
class Foo{
constructor(name) {
this.name = name;
}
sayName() {
return '这里定义的方法,相当于ES5里面的构造函数的原型方法'
}
}
let bar = new Foo('007');
console.log(bar.name) // 007
console.log(bar.sayName()) // 这里定义的方法,相当于ES5里面的构造函数的原型方法
看到这里,会发现,其实class是一个语法糖,class里面定义的方法,其实就相当于在ES5中构造函数里面的原型定义的方法一样。而在constructor里边定义的属性,就是构造函数本身的属性。
看看下面的代码
class Foo{
constructor(name) {
this.name = name;
this.test = function() {}
}
sayName() {
return '这里定义的方法,相当于ES5里面的构造函数的原型方法'
}
}
let bar = new Foo('007');
console.log(bar.hasOwnProperty('name')) // true
console.log(bar.hasOwnProperty('test')) // true
console.log(bar.hasOwnProperty('sayName')) // false
console.log(Foo.prototype.hasOwnProperty('sayName')) // true
console.log(bar.__proto__.hasOwnProperty('sayName')) // true
这段代码可以看出,上面说的准确性,在constructor里边定义的属性或者方法,是构造函数本身的,因为只有这样,构造函数的实例bar才会有相对应的属性方法(this.name和this.test会在new操作的时候将name和test绑定到bar身上,这是函数的this机制导致的)。
后面还定义了一个sayName方法,该方法不是在constructor里边定义的,所以该方法也不属于bar的,它是属于Foo的原型对象的( Foo.prototype )( bar.__proto__ 也是指向构造函数的原型 )