学习JavaScript高级第十天(原型重定向,new的实现)
1、原型重定向
function Fn(){
this.x
= 100;
}
Fn
.prototype
.getX = function(){
console
.log('原型')
};
Fn
.prototype
.z
= 300;
let f
= new Fn;
f
.getX();
Fn
.prototype
= Object
.assign(Fn
.prototype
, {
getX
: function(){
console
.log('重定向')
}
});
f
.getX();
2、new的实现过程
function Dog(name
) {
this.name
= name
;
}
Dog
.prototype
.bark = function(){
console
.log('wwww');
}
Dog
.prototype
.sayName = function(){
console
.log(this.name
);
}
function _new(Fn
, ...parms
){
let obj
= Object
.create(Fn
.prototype
);
let res
= Fn
.apply(obj
, parms
);
console
.log( typeof res
)
if((typeof res
!== 'object') && (typeof res
!== 'function')) {
return obj
;
} else return res
;
}
let sanmao
= _new(Dog
, '三毛');
console
.log(sanmao
);
sanmao
.bark();
sanmao
.sayName();
console
.log(sanmao
instanceof Dog);
Object
.create = function(obj
) {
if(typeof obj
!== 'object') {
throw new TypeError('类型错误')
}
function A(){};
A.prototype
= obj
;
return new A;
}
转载请注明原文地址: https://lol.8miu.com/read-35163.html