JavaScript 原型、原型链
什么是原型?什么是原型链?
- 
prototype:每一个对象都有它的原型对象,它可以使用原型对象上所有属性和方法!这些属性方法都定义在Object的构造器函数(constructor functions)之上的prototype属性上,而非实例对象本身。
- 
__proto__:原型对象也可能拥有原型,并从中继承方法和属性,一层一层、依次类推,这种关系常被称为原型链。对象会拥有定义在其他对象中的属性和方法
// 对象扩展
let obj = {
    name: "John"
}
obj.__proto__.getName = function () {
    console.log( this.name ); // John
}
obj.getName()
// 构造函数扩展(prototype)
const date = new Date();
Date.prototype.formate = function () {  // 原型扩展方法
    let year = this.getFullYear();
    let month = this.getMonth() + 1;
    let date = this.getDate();
    return `${ year }-${ month }-${ date }`;
}
Date.prototype.dateName = "时间对象" // 原型扩展属性
console.log( date.formate() ); // 2023-10-28 
console.log( date.dateName );  // 时间对象
获取原型对象的方法
- 
对象通过的__proto__获取 
- 
构造函数通过prototype获取 
let a = 1; // Number
console.log( a.constructor == Number ); // true
console.log( a.__proto__ === Number.prototype ); // true
let b = "2"; // String
console.log( b.constructor == String ); // true
console.log( b.__proto__ === String.prototype ); // true
let c = { a: 1 }; // Object
console.log( c.constructor == Object ); // true
console.log( c.__proto__ === Object.prototype ); // true
function fun() {} // 构造函数
console.log( fun.constructor === Function ); // true
console.log( fun.prototype.constructor === fun ); // true
let f = new fun(); // 实例化
console.log( f.constructor === fun ); // true
console.log( f.__proto__ === fun.prototype ); // true
所有原型链的终点都是 Object 函数的 prototype 属性
Objec.prototype 指向的原型对象同样拥有原型,不过它的原型是 null ,而 null 则没有原型
总结
- 每个对象都拥有一个__proto__,指向它的原型对象
- 一切对象都是继承自Object对象,Object对象直接继承根源对象null
- 原型对象默认拥有一个 constructor 属性,并指向构造函数
- 构造函数都拥有一个prototype属性,并指向原型对象
        版权声明:
        本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 
              小森森博客!
      
    喜欢就支持一下吧
      
          
          打赏
          
            
               微信
              微信
             
            
               支付宝
              支付宝
             
          
        
       微信
              微信
             支付宝
              支付宝
            