function Father(name,age){
this.name = name;
this.age = function(){
console.log(`我今年${age}岁了`);
return age
}
}
Father.prototype.job = 'cfo'
//我们通过实例化对象new出来
let son = new Father();
//有括号和没括号的区别有括号是可以进行传参的,但是也是可以进行new的
//通过new 我们可以思考下什么函数是不可以进行new的? 函数new的过程这个到底做了什么事情?
//总结来讲1 箭头函数是不可以进行new的。() => {} 2在一个就是ES6的简便语法是不可以new的
// function Simple(){
// name;
// age;
// }
// let s = new Simple();
// console.log(s.name);
//ReferenceError: age is not defined 所以会报错
所以我们通过构造函数new的过程来自己写一个new的方法
1给方法指定原函数的的原型对象
2改变this的指向
3判断构造函数,返回值是基本值,还是对象,基础值返回构造函数本身,返回值是对象则返回该对象
//判断数据类型是否是对象
function isObject(obj) {
let type = typeof obj;
return (type != null && (type === 'Object' || type === 'function'))
}
const start = function (Ctor, ...argu) {
//1让函数指向构造函数的原型
let obj = {};
obj.__proto__= Ctor.prototype
//2改变this的指向,得到函数执行的返回值,
let result = Ctor.call(obj, ...argu)//这个是call执行返回值 就是函数执行返回值
//3判断是否是对象
if (isObject(result)) return result //这里为什么要返回result
return obj
}
let end = start(Father, 'fun', 23)
console.log(end instanceof Father);//true
console.log(end.name); //fun
console.log(end.age());//我今年23了 23
未完待续