让前端飞

彻底理解js中的原型对象和prototype属性

2019-01-29  本文已影响0人  龙旗飘扬的舰队

prototype(函数的原型属性)

//prototype是函数的属性
console.log(Array.prototype.reduce.prototype);//undefined
console.log(Array.prototype.reduce);//function reduce() { [native code] }
//prototype不是实例对象的属性
function Person(name){};
var gs = new Person("gs");
console.log(gs.prototype);//undefined
function hasPrototypeProperty(obj,name){
  return name in obj && !obj.hasOwnProperty(name);//in方法,可以遍历原型属性
}

Object.getPrototypeOf 获取 prototype 属性

console.log(Object.getPrototypeOf(Person));//function () { [native code] }
console.log(Object.getPrototypeOf(Person) === Function.prototype);//true

console.log(Object.prototype);//{}
console.log(Object.getPrototypeOf({}));//{}
console.log(Object.getPrototypeOf({}) === Object.prototype);//true

Object.isPrototypeOf 获取 prototype 属性

console.log({}.isPrototypeOf({}));//false。两个空对象,无法探测原型关系
console.log(Object.prototype,Person.prototype);//两个原型都是{}的对象
console.log(Object.prototype.isPrototypeOf(Person));//true。Object是Person的原型
console.log(Object.prototype.isPrototypeOf(Person.prototype));//true。Object是{}的原型
console.log(Object.prototype.isPrototypeOf({}));//true。再次验证,Object是{}的原型

Person.prototype = function sayName(){}

prototype一般共享方法,不要共享数据

使用字面量形式可替换prototype

function Student(name,age){
  this.name = name;
  this.age = age;
}
Student.prototype = {
  constructor:Person,//使用prototype字面量时,需要手动设置constructor,否则值为 Object
  sayName:function(){
    console.log(this.name);
  },
  sayAge:function(){
    console.log(this.age);
  }
}
var zk = new Student("zk",19);
console.log(zk.constructor);//Person
console.log(zk.sayAge());

==构造函数、原型对象、对象实例三者的关系==

图一
上一篇 下一篇

猜你喜欢

热点阅读