前沿
好久没有写点东西了,最近看了下js基础教程,觉得有些东西还是有必要记录下来
关于new
new关键字通常和构造函数一起使用,用于创建对象。
function Animal(name, action) {
this.name= name;
this.action= action;
this.run= function () {
alert(this.action);
};
}
let animal1= new Animal("tigger","run");
let animal2= new Animal("cat","jump");
console.log(animal1.__proto__ === animal2.__proto__);//true
console.log(animal1.__proto__ === Animal.prototype);//true
console.log(Animal.prototype.constructor === Animal);//true
//因此person1.__proto__ = person2.__proto__ = Person
console.log(animal1.name);//yan
自己实现New
function myNew (fun, ...arg) {
// 创建一个新对象且将其隐式原型指向构造函数原型
let obj = {
__proto__: fun.prototype
}
// 执行构造函数
fun.apply(obj, arg)
// 返回该对象
return obj
}
function Person (name, age) {
this.name = name ;
this.age = age
}
let _person = myNew(Person, 'huang', '21')
console.log(_person)