1. 原型

原型【**函数**的属性】Prototype

创建的每一个函数,解析器都会向函数中添加一个属性prototype。这个属性对应一个对象,这个对象就是原型对象。

如果函数作为普通函数调用prototype没有任何作用。

当函数以构造函数形式调用时,它创建的对象都有一个隐含属性

访问该属性: 对象.__proto__

  • 原型对象相当于一个公共区域,所有同一个类的实例都可以访问这个原型对象。我们可以将对象中共有的内容,统一设置到原型对象中。
  • 当访问对象的属性或方法时,会先在对象自身中寻找,如果有则直接使用,如果没有则去原型中寻找。

image-20211108112911954

//实例对象的原型对象 == 函数的原型对象 【公共区域】
function MyClass (){
    this.a = 233;    
}
var mc = new MyClass();
var mc2 = new MyClass();
console.log(mc.__proto__ == mc2.__proto__); //true
mc.a = 666;
MyClass.prototype.a = 555;
MyClass.prototype.b = 777;
console.log(mc.a +"  " +mc2.a); //666   233
console.log(mc.a +"  " +mc2.b); //666   777

2. 原型的原型

原型的原型:

当使用一个对象的属性或方法时,会先在自身寻找。

自身中有,则直接使用;

没有,则去原型对象中寻找。如果还没有,

则去原型的原型中寻找,直到找到Object对象的原型

Object对象的原型没有原型,如果在Object中依然没有找到,则返回 undefined

"属性" in 对象; //检查某个属性时,对象中没有但原型中有,也会返回 true.

hasOwnProperty()方法:【验证是否实例自身还有某个属性(方法以及项)。】

function MyClass (){
    this.a = 233;    
}
var mc = new MyClass();
var mc2 = new MyClass();
//实例自身是否含有 某个属性
console.log(mc.__proto__.hasOwnProperty("hasOwnProperty"));
console.log(mc.__proto__.__proto__.hasOwnProperty("hasOwnProperty"));

//mc的原型对象的原型对象 是object
console.log("原型对象的原型对象类型: "+typeof mc.__proto__.__proto__.__proto__); //object
//原型对象。 mc的原型对象的原型对象。类型 "Object"。prototype是null===>不是函数。
console.log("原型对象的原型对象de原型对象。: "+mc.__proto__.__proto__.__proto__);//null

//mc的原型对象 == MyClass的原型对象 
console.log("mc的原型对象与 MyClass的原型对象 的xxxx:"+(mc.__proto__.prototype == MyClass.prototype.prototype)); // xxxxxxxtrue

//函数才有prototype属性。实例对象 对应的是__proto__属性。
console.log(typeof mc.prototype ); //undefined
console.log(typeof MyClass.prototype); // object

//MyClass的原型对象的原型对象: undefined。=======> MyClass的原型对象不是 “函数”
console.log(MyClass.prototype.prototype); //

3. 修改原型的方法

function Person (name,age,gender){
    this.a = 233;    
    this.name = name;
    this.age = age;
    this.gender =gender;
}
//添加原型对象的方法。 会“覆盖”掉原型的原型的方法
Person.prototype.toString = function (){
    return "我时prototype的toString";
}

var mc = new Person();

console.log(mc);//Person { a: 233, name: undefined, age: undefined, gender: undefined }
console.log(mc.toString()); //我时prototype的toString
console.log(mc.__proto__.__proto__.hasOwnProperty("toString")); //true
最后修改:2022 年 01 月 12 日
如果觉得我的文章对你有用,请随意赞赏