JS中 对象被创建出来时,都有一个对应的原型(prototype)属性,使对象可以共享原型的属性和方法。减少不必要的内存消耗。
构造函数-- 使用new 创建对象的函数
function Person(name,age){
this.name = name;
this.age = age;
}
let p1 = new Person('张三',14)
let p2 = new Person('李四',15);
console.log(p1,p2);
Person.prototype.sing = function(){ //共享属性
console.log('我会唱歌');
}
p1.sing();
p2.sing();
console.log(p1.__proto__===Person.prototype);
// p1本身上没有sing方法,它通过p1.__proto__ 到Person.prototype原型中去查找
//还找不到的话,就继续去原型的原型上找,直到原型的末端
console.log(Object.prototype.__proto__ ===null);//true
function Person() {}
console.log(Person.prototype.__proto__ === Object.prototype) // 输出true
'[Object String]'
instanceof原理
判断指定构造函数的原型对象是否出现在实例的原型链上。
// 判断指定构造函数的原型对象是否出现在指定对象的原型链上
function Test(name){
this.name = name;
}
Test.prototype.sing=function(){
console.log(this.name);
}
const t = new Test(1);
console.log(t instanceof Test);
myInstanceof = function(obj,con){
let obj__proto__ = obj.__proto__;
while(true){
if(obj__proto__ === con.prototype)
{
return true;
}
if(obj__proto__===null){
return false;
}
obj__proto__ = obj__proto__.__proto__;
}
}
console.log(myInstanceof('123',String))