Chapter9 Classes,Constructor, and Prototypes - - - Prototypes and Inheritance

本文探讨JavaScript中的对象方法实现与继承机制。介绍了如何利用构造函数和原型对象为对象添加方法,对比了不同方法的优劣,并详细解释了原型链的工作原理。

9.2  Prototypes and Inheritance


     方法就是一个函数且被调用时作为对象的属性。当一个函数像这样子被调用,通过它访问的对象会成为this关键字的值。

     那么我们用Rectangle object去表达rectangle的area方法。其中一种方式是:

     

function computeAreaOfRectangle(r){
 return r.width * r.height;
}

     这种就不是面向对象的了。当我们去使用objects的时候,最好就是调用对象的方法而不是传给函数一个对象。我们可以这样做:


//Create a Rectangle object
var r = new Rectangle(8.5, 11);
//Add a method to it
r.area = function() {return this.width * this. height;}
//Now invoke the method to compute the area
var a = r.area();

     在你去调用之前我们不得不去添加一个方法给对象时,这是愚蠢的。当然,我们可以通过初始化area属性去指向在构造函数中的area的执行函数;这就是一个改进的Rectangle的构造函数;

    

function Rectangle(w,h){
    this.width = w;
    this.height = h;
    this.area = function() {return this.width * this.height;}
}

那么我们就可以这样执行:

var r = new Rectangle(8.5, 11);
var a = r.area();

      这中方法比之前的好但不是最理想的,每一个rectangle对象被创建时,都将有3个属性。那么width和height属性对于每一个retangle对象来说都可能不一样,但area总是指向用一个函数。(要是有人去修改了这个函数,那就悲剧了!当然我们总是希望它不会变。)一个属性经常性被来自于同一个类的所有对象作为方法去使用是无效率的。

      解决的办法是,事实证明每个JavaScript对象都包含了一个内部引用指向另一个对象,被称为prototype对象。下面书中的这句话比较难翻译,大概意思就是一个JavaScript对象继承它的prototype里的属性。

      还记得前面一段吗?new一个空对象且调用其构造函数作为该对象的方法。然而这并不完全,在创建一个空对象后,new表达式会设置该对象的prototype,一个对象的prototype是它的构造函数里的prototype属性的值。所有函数都有一个prototype属性且当这个函数被定义时,该prototype属性就会自动被创建和初始化。prototype属性的初始值就是一个有这单个属性的对象。这个属性就是叫构造函数,并且会回指向与该构造函数相关联的prototype.(应该就是指prototype对象的构造函数)。当然当你添加属性到这个prototype里时,这些属性将会在构造函数中被初始化。

     那么我们就再使用prototype来改下Rectangle这个构造函数;

     

function Rectangle(w, h) {
    this.width = w;
    this.height = h;
}

//The prototype object holds methods and other properties that 
//should be shared by each instance
Rectangle.prototype.area = function(){
  return this.width * this.height;
}

   prototype属性是与构造函数想关联的,每个被构造函数初始化的对象都从prototype那继承了一些属性,这说明了prototype对象对于方法和一些常量属性是一个理想的地方。

请注意,在查找属性的值的过程就已经自动地发生继承。属性并非是从prototype对象里copy到新的对象的。它们就好像是那些对象的属性。这里有两个重要的含义,第一,

prototype对象的用法可以大大的减少了许多对象所需要的内存空间,因为对象是可以继承很多prototype的属性。第二个就是一个对象甚至可以继承那些在对象被创建后才添加到它的prototype的属性。

    Object.hasOwnProperty方法就是识别属性是否在对象里。

    

var r = new Rectangle(2,3);

r.hasOwnProperty("width"); // true
r.hasOwnProperty("area");  // false
"area" in r;  // true



03-14
### Prototype-Based Programming Prototype-based programming is a style of object-oriented programming where inheritance happens through prototyping rather than class definitions. In this paradigm, objects inherit directly from other objects without requiring an explicit class definition or hierarchy[^1]. This approach allows developers to create flexible and dynamic systems by modifying prototypes at runtime. In JavaScript, the concept of **prototype** plays a crucial role as it defines how properties and methods are shared among objects. Every function in JavaScript has a `prototype` property which refers to an object (the prototype). When creating instances using constructors like `new`, these newly created objects internally reference their constructor's prototype for method resolution[^2]. Here’s an example demonstrating basic usage: ```javascript function Person(name) { this.name = name; } // Adding a method via the prototype chain. Person.prototype.greet = function () { console.log(`Hello, my name is ${this.name}.`); }; const personInstance = new Person('Alice'); personInstance.greet(); // Output: Hello, my name is Alice. ``` The above code snippet shows that adding functions onto the `prototype` ensures they can be accessed across multiple instances efficiently while avoiding redundant memory allocation per instance. Additionally, understanding the distinction between functional versus imperative paradigms helps contextualize why certain languages adopt specific design patterns such as those involving prototypes over traditional classes found within statically-typed counterparts[^3]: For file handling operations typically seen under procedural constructs inside C++, one would utilize streams provided either natively (`iostream`) or indirectly when dealing with strings/file contents manipulation tasks utilizing specialized libraries built around them e.g., `fstream`, etc.[^4]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值