原生JS写new
new()方法在生成一个实例时做了什么:
- 创建一个空对象
- 将构造函数的作用域赋给新对象
- 执行构造函数(为这个新对象添加属性)
- 返回新对象
funtion Person(name,age){
this.name = name;
this.age = age;
}
Person.property.sayName = function(){
console.log('say hi!')
}
var person1 = new Person('amy',26)
console.log(person1.name)
person1.sayName()
// ES5构造函数
let Person = function (name, age) {
this.name = name;
this.age = age;
};
Person.prototype.sayName = function () {
console.log(this.name);
};
const child = new Person('听风是风', 26);
child.sayName() //'听风是风'
//ES6 class类
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayName() {
console.log(this.name);
}
};
const child = new Person('echo', 26);
child.sayName() //echo
思考:如果调用Person()方法时,不用new Person()方法,而是直接调用Person()会是什么结果?
如何避免用户直接调用,导致出现无法实例的情况
funtion Person(name,age){
if (!(this instanceof Person)) {
return new Person(name,age);
}
this.name = name;
this.age = age;
}
Person.property.sayName = function(){
console.log('say hi!')
}
var person1 = new Person('amy',26)
console.log(person1.name)
person1.sayName()
用js实现new()的过程
const Person = function (name,age) {
this.name = name;
this.age = age;
};
Person.prototype.say = function(){
console.log(this.name)
}
//实现过程
function myNew(fn,...arg){
// 1.以构造器的prototype属性为原型,创建新对象;
let obj = Object.create(fn.prototype)
// 2.将this和调用参数传给构造器执行
let result = fn.apply(obj,arg)
// 3.如果构造器没有手动返回对象,则返回第一步的对象
return typeof result === 'object' ? result : obj;
}
let demo = myNew(Animals,'cat')
console.log(demo.name)
console.log(demo.say())