前言
这篇文章是关于构造函数知识篇章
原型属性
- 构造函数在被
new
时把构造函数的原型(prototype
)赋值给新对象 - 如果对象中存在属性将使用对象属性,不再原型上查找方法
- 构造函数只会产生一个原型对象
- 对象的原型引用构造函数的原型对象,是在创建对象时确定的,当构造函数原型对象改变时会影响后面的实例对象
constructor
构造函数的原型中包含属性 constructor 指向该构造函数
function User(name) {
this.name = name;
}
let xb = new User("xb");
let t = new xb.constructor("tttt");
console.log(t);
直接设置了构造函数的原型将造成 constructor 丢失
function User(name) {
this.name = name;
}
//错误的设置构造函数方式
User.prototype = {
show: function() {}
};
let xb = new User("xb");
let t = new xb.constructor("tttt");
console.log(t); //String {'tttt'}
//正确的方式
User.prototype = {
constructor: User,//将constructor重新指向构造函数
show: function() {}
};
体验继承
下面为 Student
更改了原型为User
的实例对象,ls
是通过构造函数Student
创建的实例对象
- ls在执行getName 方法时会从自身并向上查找原型,这就是原型链特性
- 当然如果把 getName 添加到对象上,就不继续追溯原型链了
function User() {}
User.prototype.getName = function() {
return this.name;
};
function Student(name) {
this.name = name;
}
Student.prototype = new User();
const ls = new Student("李四");
console.log(ls.__proto__);
console.log(ls.getName());