1. Create an empty object.
<script>
function Foo(){
}
console.log(new Foo());//Foo{}
</script>
2. Point the prototype of the empty object to the prototype of the constructor.
<script>
function Foo(){
}
console.log(Foo.prototype == new Foo().__proto__);//true
</script>
3. Use the empty object as the context of the constructor (change this point).
<script>
function Foo(){
console.log(this);//window
this.name = '张山';
}
console.log(Foo());//undefined
</script>
<script>
function Foo(){
console.log(this);//Foo{}
this.name = '张山';
}
console.log(new Foo());//Foo{name:'张山'}
</script>
Fourth, the processing of the return value of the constructor.
If the constructor is a basic type, ignore it; if it is a reference type, use return to return.
<script>
function Foo(){
this.name = '张山';
return 11
}
console.log(new Foo());//Foo{name:'张山'}
</script>
<script>
function Foo(){
this.name = '张山';
return {}
}
console.log(new Foo());//{}
</script>
<script>
function Foo(){
this.name = '张山';
return [1,2,3],
}
console.log(new Foo());//[1,2,3]
</script>
5. Implement a constructor yourself.
<script>
function Fun(age,name){
this.age = age;
this.name = name;
}
function create(fn,...args){
//创建一个空对象
var obj = {};//var obj = Object.create({});
//将空对象的原型,指向于构造函数的原型
Object.setPrototypeOf(obj,fn.prototype);
//改变this指向
var result = fn.apply(obj,args);
//对构造函数有返回值的处理
return result instanceof Object ? result : obj;
}
console.log(create(Fun,18,'张山'));//Fun{age:18,name:'张山'}
</script>