先看一段代码
function People(name, age) {
this.name = name;
this.age = age;
}
People.prototype.run = function() {
return "i im run --";
};
function Student(name, age, sex) {
People.call(this, name, age);
this.sex = sex;
}
Student.prototype.speak = function() {
return "i im speak";
};
let s1 = new Student("悟空", 23);
console.log('s1.name',s1.name);
console.log('s1.speak',s1.speak());
new了之后返回了一个对象,该对象可以调用构造函数的方法,以及原型的方法
我们试着来实现
function customizeNew(Sup) {
let Sub = {}; //新建一个对象
Sub.__proto__ = Sup.prototype; //对象的原型指向其构造函数
Sub.constructor = Sup;
return function() {
Sup.apply(Sub, arguments);
return Sub;
};
}
let s2 = customizeNew(Student)("悟空", 24);
__proto__ 是不建议使用的,推荐使用Object.create(),晚点我们来看下用这个怎么实现
评论
使用 GitHub 账号登录后即可评论