Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Подробнее об объектной модели

Перевод не завершен. Пожалуйста, помогите перевести эту статью с английского.

JavaScript это объектно-ориентированный язык основанный на прототипировании, а не на основе классов. Из-за этого различия может быть менее очевидно, как JavaScript позволяет создавать иерархии объектов и иметь наследование свойств и значений. В этой главе мы попытаемся объяснить вам это отличие.

Языки, основанные на классах vs. Прототипно-ориентированные языки

Основанные на классах объектно-ориентированные языки программирования, такие как Java и C++, основаны на концепции двух отдельных сущностей: классах и экземплярах объектов.

  • Класс определяет все свойства (учитывая методы и все поля в  Java, или свойства в C++) которые характеризует особый набор свойств. Класс это абстрактная вещь, а не какой-либо из частей, которая описывает объект. Например, класс Employee может быть представлен набором всех сотрудников.
  • Экземпляр, это объект класса; тоесть один из его членов. Например, Виктория может быть экземпляром класса Employee, представляющее собой конкретное отдельное лицо. Экземпляр класса имеет ровно столько свойст, сколько и родительский класс (не больше и не меньше).

Прототипно-ориентированные языки, такие как, например JavaScript, не реализует данное различие: это просто объекты. Языки основанные на прототипах имеют понятие прототипа объекта — это объект, используемый в качестве шаблона, с целью получить изначальные свойства для нового объекта. Любой объект может иметь собственные свойства, присвоенные либо во время создания, либо во время выполнения. В дополнение, любой объект может быть указан в качестве прототипа для другого объекта, это позволит второму объекту использовать свойства первого.

Определение класса

В классо-ориентированных языках, вы можете определить класс. В этом определении вы можете указать специальные методы, называемые конструкторами, которые позволят создать экземпляр класса. Метод конструктор может может задать начальные значения для свойств экземпляра и выполнять другие действия, в момент создания. Вы можете использовать оператор  new , совместно с методом конструктора, для создания экземпляров классов.

JavaScript использует похожую модель, но не имеет отдельного  конструктора для создания классов. Вместо этого, вы определяете функцию конструктора для создания объектов с особым начального набора свойств и значений. Любая функция в JavaScript может быть использована, как конструктор. Вы должны использовать оператор new для создания нового объекта.

Подклассы и наследование

В языках, основанных на классах, вы создаете иерархию классов, через объявление классов. В объявлении класса, вы можете указать, что новый класс является подклассом уже существующего класса. Подклассом наследуют все свойства суперкласса и в дополнение можно добавлять новые свойства или же переопределять унаследованные. Например, предположим класс Employee включает только свойства имя и отдел, и Manager подкласс Employee с добавленным свойством отчеты. В этом случае, экземпляр класса Manager будет иметь все три свойства: имя, отдел, и отчеты.

JavaScript реализует наследование, позволяя связать прототип объекта с любой функцией конструктора. Итак, вы можете создать точь-в-точь, как в примере Employee — Manager, но используя несколько иную терминологию. Для начала нужно определить функцию-конструктор Employee, с указанием свойств имя и отдел. Затем, вы создаете функцию-конструктор Manager, вызывая конструктор Employee и указав свойство отчеты. Наконец, вы назначаете новый объект производный от Employee.prototype как prototype для функции-конструктора Manager. Затем, когда вы создаете нового Manager, он наследует свойства имя и отдела из объекта Employee.

Добавление и удаление свойств

В языках, основанных на классах, вы, как правило, создаете класс во время компиляции, а затем вы создаёте экземпляры класса либо во время компиляции, или во время выполнения. Вы не можете изменить количество или тип свойств класса после определения класса. В JavaScript, однако, вы можете добавлять или удалять свойства любого объекта. Если вы добавляете свойство к объекту, который используется в качестве прототипа для множества объектов, объекты, для которых он является прототипом и получить новое свойство.

Подытожим различия

Следующая таблица дает краткий обзор некоторых из этих различий. А оставшаяся часть этой главы описывает детали использования конструкторов и прототипов JavaScript для создания иерархии объектов и сравнивает это с тем, как вы могли бы сделать это в Java.

Table 8.1 Сравнение языков на основе классов (Java) и на базе прототипов (JavaScript)
Основанные на классах (Java) Основанные на базе прототипов (JavaScript)
Класс и экземпляр являются разными лицами. Все объекты могут наследовать от другого объекта
Класс определяется с помощью определения класса; экземпляр класса с помощью метода-конструктора. Определение и создание объекта происходит с помощью функций-конcтрукторов.
Создание единого объекта с помощью опреатора new. Так же.
Иерархия объектов строится с помощью построения классов и определения подклассов.

Построение иерархии объектов происходит путем присвоения объекта в качестве прототипа, связывания с функцией конструктора.

Наследование свойств в цепочке класса. Наследование свойств в цепочке прототипов.
Определение класса определяет все свойства всех экземпляров класса. Нельзя динамически добавлять свойства во время выполнения. Функция-конструктор или прототип задает начальный набор свойств. Можно добавить или удалить свойства динамически к отдельным объектам или всей совокупности объектов.

Пример Сотрудник

Оставшаяся часть этой главы объясняет иерархию сотрудников, показанный на следующем рисунке.

Рисунок 8.1: Простая иерархия объекта

Этот пример использует следующие объекты:

  • Employee имеет свойство name (значение которого по умолчанию пустая строка) и dept (значение которого по умолчанию "general").
  • Manager основывается на Employee. Он добавляет свойство reports (значение которого по умолчанию пустой массив, предназначенный для хранения массива объектов Employee).
  • WorkerBee так же основан на Employee. Он добавляет свойство projects (значение которого по умолчанию пустой массив, предназначенный для хранения строк).
  • SalesPerson основан на WorkerBee. Он добавляет свойство quota (значение которого по умолчанию 100). Он также переопределяет свойство dept, со значением "sales", указывая, что все продавцы находятся в том же отделе.
  • Engineer основан на WorkerBee. Он добавляет свойство machine (значение которого по умолчанию пустая строка) а так же определяет свойство dept значением "engineering".

Создание иерархии

Известно множество способов определить подходящие конструктора функций чтобы реализовать иерархию прототипа Employee. Выбор способа определения в большей степени зависит от того на что рассчитано ваше приложение.

Этот раздел объясняет, как использовать очень простые (но не гибкие в настройке) описания, для демонстрации того, как же работает наследование. В этих описаниях, вы не можете указать перснональные значения свойств при создании объекта. Вновь созданный объект просто получает свои значения по умолчанию, которые можно изменить позднее.

В реальном приложении, вы, вероятно, будете определять конструкторы, которые позволяют устанавливать нужные вам значения свойств во время создания объекта (см Более гибкие конструкторы для информации). Но пока что, эти простые примеры демонстрируют, как происходит наследование.

Следующие определения Employee похожи для Java и JavaScript. Единственное отличие состоит в том, что вам необходимо указать тип каждого свойства в Java, но не в JavaScript (потому что Java является строго типизированным языком, в то время как JavaScript является слабо типизированным языком).

JavaScript Java
function Employee() {
  this.name = "";
  this.dept = "general";
}
public class Employee {
   public String name = "";
   public String dept = "general";
}

Определения классов Manager и WorkerBee показывают разницу в том, как задать вышестоящий объект в цепочке наследования. В JavaScript вы добавляете прототипип класса в качестве аргумента для функции конструктора наследника. Вы можете сделать это в любое время после того, как вы создали конструктор. В Java, необходимо указать суперкласс внутри определения класса. Вы не можете изменить суперкласс вне определения класса.

JavaScript Java
function Manager() {
  Employee.call(this);
  this.reports = [];
}
Manager.prototype = Object.create(Employee.prototype);

function WorkerBee() {
  Employee.call(this);
  this.projects = [];
}
WorkerBee.prototype = Object.create(Employee.prototype);
public class Manager extends Employee {
   public Employee[] reports = new Employee[0];
}

public class WorkerBee extends Employee {
   public String[] projects = new String[0];
}

Классы Engineer и SalesPerson создают объекты, которые происходят от WorkerBee и, следовательно, от Employee. Объект этих типов имеет свойства всех объектов, расположенных над ним в иерархии. Также, эти классы переопределяют наследуемое значение свойства dept своими значениями, характерными для этих объектов.

JavaScript Java
function SalesPerson() {
   WorkerBee.call(this);
   this.dept = "sales";
   this.quota = 100;
}
SalesPerson.prototype = Object.create(WorkerBee.prototype);

function Engineer() {
   WorkerBee.call(this);
   this.dept = "engineering";
   this.machine = "";
}
Engineer.prototype = Object.create(WorkerBee.prototype);
public class SalesPerson extends WorkerBee {
   public double quota;
   public dept = "sales";
   public quota = 100.0;
}

public class Engineer extends WorkerBee {
   public String machine;
   public dept = "engineering";
   public machine = "";
}
   

Using these definitions, you can create instances of these objects that get the default values for their properties. Figure 8.3 illustrates using these JavaScript definitions to create new objects and shows the property values for the new objects.

Примечание: The term instance has a specific technical meaning in class-based languages. In these languages, an instance is an individual instantiation of a class and is fundamentally different from a class. In JavaScript, "instance" does not have this technical meaning because JavaScript does not have this difference between classes and instances. However, in talking about JavaScript, "instance" can be used informally to mean an object created using a particular constructor function. So, in this example, you could informally say that jane is an instance of Engineer. Similarly, although the terms parent, child, ancestor, and descendant do not have formal meanings in JavaScript; you can use them informally to refer to objects higher or lower in the prototype chain.

figure8.3.png
Рисунок 8.3: Создание объектов с простыми определениями

Свойства объекта

This section discusses how objects inherit properties from other objects in the prototype chain and what happens when you add a property at run time.

Наследование свойств

Suppose you create the mark object as a WorkerBee (as shown in Figure 8.3) with the following statement:

var mark = new WorkerBee;

When JavaScript sees the new operator, it creates a new generic object and passes this new object as the value of the this keyword to the WorkerBee constructor function. The constructor function explicitly sets the value of the projects property, and implicitly sets the value of the internal __proto__ property to the value of WorkerBee.prototype. (That property name has two underscore characters at the front and two at the end.) The __proto__ property determines the prototype chain used to return property values. Once these properties are set, JavaScript returns the new object and the assignment statement sets the variable mark to that object.

This process does not explicitly put values in the mark object (local values) for the properties that mark inherits from the prototype chain. When you ask for the value of a property, JavaScript first checks to see if the value exists in that object. If it does, that value is returned. If the value is not there locally, JavaScript checks the prototype chain (using the __proto__ property). If an object in the prototype chain has a value for the property, that value is returned. If no such property is found, JavaScript says the object does not have the property. In this way, the mark object has the following properties and values:

mark.name = "";
mark.dept = "general";
mark.projects = [];

The mark object inherits values for the name and dept properties from the prototypical object in mark.__proto__. It is assigned a local value for the projects property by the WorkerBee constructor. This gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in Property inheritance revisited.

Because these constructors do not let you supply instance-specific values, this information is generic. The property values are the default ones shared by all new objects created from WorkerBee. You can, of course, change the values of any of these properties. So, you could give specific information for mark as follows:

mark.name = "Doe, Mark";
mark.dept = "admin";
mark.projects = ["navigator"];

Добавление свойств

In JavaScript, you can add properties to any object at run time. You are not constrained to use only the properties provided by the constructor function. To add a property that is specific to a single object, you assign a value to the object, as follows:

mark.bonus = 3000;

Now, the mark object has a bonus property, but no other WorkerBee has this property.

If you add a new property to an object that is being used as the prototype for a constructor function, you add that property to all objects that inherit properties from the prototype. For example, you can add a specialty property to all employees with the following statement:

Employee.prototype.specialty = "none";

As soon as JavaScript executes this statement, the mark object also has the specialty property with the value of "none". The following figure shows the effect of adding this property to the Employee prototype and then overriding it for the Engineer prototype.


Рисунок 8.4: Добавление свойств

Более гибкие конструкторы

The constructor functions shown so far do not let you specify property values when you create an instance. As with Java, you can provide arguments to constructors to initialize property values for instances. The following figure shows one way to do this.


Figure 8.5: Specifying properties in a constructor, take 1

The following table shows the Java and JavaScript definitions for these objects.

JavaScript Java
function Employee (name, dept) {
  this.name = name || "";
  this.dept = dept || "general";
}
public class Employee {
   public String name;
   public String dept;
   public Employee () {
      this("", "general");
   }
   public Employee (String name) {
      this(name, "general");
   }
   public Employee (String name, String dept) {
      this.name = name;
      this.dept = dept;
   }
}
function WorkerBee (projs) {
 
 this.projects = projs || [];
}
WorkerBee.prototype = new Employee;
public class WorkerBee extends Employee {
   public String[] projects;
   public WorkerBee () {
      this(new String[0]);
   }
   public WorkerBee (String[] projs) {
      projects = projs;
   }
}

 
function Engineer (mach) {
   this.dept = "engineering";
   this.machine = mach || "";
}
Engineer.prototype = new WorkerBee;
public class Engineer extends WorkerBee {
   public String machine;
   public Engineer () {
      dept = "engineering";
      machine = "";
   }
   public Engineer (String mach) {
      dept = "engineering";
      machine = mach;
   }
}

These JavaScript definitions use a special idiom for setting default values:

this.name = name || "";

The JavaScript logical OR operator (||) evaluates its first argument. If that argument converts to true, the operator returns it. Otherwise, the operator returns the value of the second argument. Therefore, this line of code tests to see if name has a useful value for the name property. If it does, it sets this.name to that value. Otherwise, it sets this.name to the empty string. This chapter uses this idiom for brevity; however, it can be puzzling at first glance.

Примечание: This may not work as expected if the constructor function is called with arguments which convert to false (like 0 (zero) and empty string (""). In this case the default value will be chosen.

With these definitions, when you create an instance of an object, you can specify values for the locally defined properties. As shown in Figure 8.5, you can use the following statement to create a new Engineer:

var jane = new Engineer("belau");

Jane's properties are now:

jane.name == "";
jane.dept == "engineering";
jane.projects == [];
jane.machine == "belau"

Notice that with these definitions, you cannot specify an initial value for an inherited property such as name. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.

So far, the constructor function has created a generic object and then specified local properties and values for the new object. You can have the constructor add more properties by directly calling the constructor function for an object higher in the prototype chain. The following figure shows these new definitions.


Figure 8.6 Specifying properties in a constructor, take 2

Let's look at one of these definitions in detail. Here's the new definition for the Engineer constructor:

function Engineer (name, projs, mach) {
  this.base = WorkerBee;
  this.base(name, "engineering", projs);
  this.machine = mach || "";
}

Suppose you create a new Engineer object as follows:

var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");

JavaScript follows these steps:

  1. The new operator creates a generic object and sets its __proto__ property to Engineer.prototype.
  2. The new operator passes the new object to the Engineer constructor as the value of the this keyword.
  3. The constructor creates a new property called base for that object and assigns the value of the WorkerBee constructor to the base property. This makes the WorkerBee constructor a method of the Engineer object.The name of the base property is not special. You can use any legal property name; base is simply evocative of its purpose.
  4. The constructor calls the base method, passing as its arguments two of the arguments passed to the constructor ("Doe, Jane" and ["navigator", "javascript"]) and also the string "engineering". Explicitly using "engineering" in the constructor indicates that all Engineer objects have the same value for the inherited dept property, and this value overrides the value inherited from Employee.

  5. Because base is a method of Engineer, within the call to base, JavaScript binds the this keyword to the object created in Step 1. Thus, the WorkerBee function in turn passes the "Doe, Jane" and "engineering" arguments to the Employee constructor function. Upon return from the Employee constructor function, the WorkerBee function uses the remaining argument to set the projects property.
  6. Upon return from the base method, the Engineer constructor initializes the object's machine property to "belau".
  7. Upon return from the constructor, JavaScript assigns the new object to the jane variable.

You might think that, having called the WorkerBee constructor from inside the Engineer constructor, you have set up inheritance appropriately for Engineer objects. This is not the case. Calling the WorkerBee constructor ensures that an Engineer object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the Employee or WorkerBee prototypes, those properties are not inherited by the Engineer object. For example, assume you have the following statements:

function Engineer (name, projs, mach) {
  this.base = WorkerBee;
  this.base(name, "engineering", projs);
  this.machine = mach || "";
}
var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
Employee.prototype.specialty = "none";

The jane object does not inherit the specialty property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:

function Engineer (name, projs, mach) {
  this.base = WorkerBee;
  this.base(name, "engineering", projs);
  this.machine = mach || "";
}
Engineer.prototype = new WorkerBee;
var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
Employee.prototype.specialty = "none";

Now the value of the jane object's specialty property is "none".

Another way of inheriting is by using the call() / apply() methods. Below are equivalent:

function Engineer (name, projs, mach) {
  this.base = WorkerBee;
  this.base(name, "engineering", projs);
  this.machine = mach || "";
}
function Engineer (name, projs, mach) {
  WorkerBee.call(this, name, "engineering", projs);
  this.machine = mach || "";
}

Using the javascript call() method makes a cleaner implementation because the base is not needed anymore.

Тонкости наследования свойств

The preceding sections described how JavaScript constructors and prototypes provide hierarchies and inheritance. This section discusses some subtleties that were not necessarily apparent in the earlier discussions.

Local versus inherited values

When you access an object property, JavaScript performs these steps, as described earlier in this chapter:

  1. Check to see if the value exists locally. If it does, return that value.
  2. If there is not a local value, check the prototype chain (using the __proto__ property).
  3. If an object in the prototype chain has a value for the specified property, return that value.
  4. If no such property is found, the object does not have the property.

The outcome of these steps depends on how you define things along the way. The original example had these definitions:

function Employee () {
  this.name = "";
  this.dept = "general";
}

function WorkerBee () {
  this.projects = [];
}
WorkerBee.prototype = new Employee;

With these definitions, suppose you create amy as an instance of WorkerBee with the following statement:

var amy = new WorkerBee;

The amy object has one local property, projects. The values for the name and dept properties are not local to amy and so are gotten from the amy object's __proto__ property. Thus, amy has these property values:

amy.name == "";
amy.dept == "general";
amy.projects == [];

Now suppose you change the value of the name property in the prototype associated with Employee:

Employee.prototype.name = "Unknown"

At first glance, you might expect that new value to propagate down to all the instances of Employee. However, it does not.

When you create any instance of the Employee object, that instance gets a local value for the name property (the empty string). This means that when you set the WorkerBee prototype by creating a new Employee object, WorkerBee.prototype has a local value for the name property. Therefore, when JavaScript looks up the name property of the amy object (an instance of WorkerBee), JavaScript finds the local value for that property in WorkerBee.prototype. It therefore does not look farther up the chain to Employee.prototype.

If you want to change the value of an object property at run time and have the new value be inherited by all descendants of the object, you cannot define the property in the object's constructor function. Instead, you add it to the constructor's associated prototype. For example, assume you change the preceding code to the following:

function Employee () {
  this.dept = "general";
}
Employee.prototype.name = "";

function WorkerBee () {
  this.projects = [];
}
WorkerBee.prototype = new Employee;

var amy = new WorkerBee;

Employee.prototype.name = "Unknown";

In this case, the name property of amy becomes "Unknown".

As these examples show, if you want to have default values for object properties and you want to be able to change the default values at run time, you should set the properties in the constructor's prototype, not in the constructor function itself.

Determining instance relationships

Property lookup in JavaScript looks within an object's own properties and, if the property name is not found, it looks within the special object property __proto__. This continues recursively; the process is called "lookup in the prototype chain".

The special property __proto__ is set when an object is constructed; it is set to the value of the constructor's prototype property. So the expression new Foo() creates an object with __proto__ == Foo.prototype. Consequently, changes to the properties of Foo.prototype alters the property lookup for all objects that were created by new Foo().

Every object has a __proto__ object property (except Object); every function has a prototype object property. So objects can be related by 'prototype inheritance' to other objects. You can test for inheritance by comparing an object's __proto__ to a function's prototype object. JavaScript provides a shortcut: the instanceof operator tests an object against a function and returns true if the object inherits from the function prototype. For example,

var f = new Foo();
var isTrue = (f instanceof Foo);

For a more detailed example, suppose you have the same set of definitions shown in Inheriting properties. Create an Engineer object as follows:

var chris = new Engineer("Pigman, Chris", ["jsd"], "fiji");

With this object, the following statements are all true:

chris.__proto__ == Engineer.prototype;
chris.__proto__.__proto__ == WorkerBee.prototype;
chris.__proto__.__proto__.__proto__ == Employee.prototype;
chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype;
chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null;

Given this, you could write an instanceOf function as follows:

function instanceOf(object, constructor) {
   object = object.__proto__;
   while (object != null) {
      if (object == constructor.prototype)
         return true;
      if (typeof object == 'xml') {
        return constructor.prototype == XML.prototype;
      }
      object = object.__proto__;
   }
   return false;
}
Note: The implementation above checks the type of the object against "xml" in order to work around a quirk of how XML objects are represented in recent versions of JavaScript. See баг 634150 if you want the nitty-gritty details.

Using the instanceOf function defined above, these expressions are true:

instanceOf (chris, Engineer)
instanceOf (chris, WorkerBee)
instanceOf (chris, Employee)
instanceOf (chris, Object)

But the following expression is false:

instanceOf (chris, SalesPerson)

Global information in constructors

When you create constructors, you need to be careful if you set global information in the constructor. For example, assume that you want a unique ID to be automatically assigned to each new employee. You could use the following definition for Employee:

var idCounter = 1;

function Employee (name, dept) {
   this.name = name || "";
   this.dept = dept || "general";
   this.id = idCounter++;
}

With this definition, when you create a new Employee, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement is the following, victoria.id is 1 and harry.id is 2:

var victoria = new Employee("Pigbert, Victoria", "pubs")
var harry = new Employee("Tschopik, Harry", "sales")

At first glance that seems fine. However, idCounter gets incremented every time an Employee object is created, for whatever purpose. If you create the entire Employee hierarchy shown in this chapter, the Employee constructor is called every time you set up a prototype. Suppose you have the following code:

var idCounter = 1;

function Employee (name, dept) {
   this.name = name || "";
   this.dept = dept || "general";
   this.id = idCounter++;
}

function Manager (name, dept, reports) {...}
Manager.prototype = new Employee;

function WorkerBee (name, dept, projs) {...}
WorkerBee.prototype = new Employee;

function Engineer (name, projs, mach) {...}
Engineer.prototype = new WorkerBee;

function SalesPerson (name, projs, quota) {...}
SalesPerson.prototype = new WorkerBee;

var mac = new Engineer("Wood, Mac");

Further assume that the definitions omitted here have the base property and call the constructor above them in the prototype chain. In this case, by the time the mac object is created, mac.id is 5.

Depending on the application, it may or may not matter that the counter has been incremented these extra times. If you care about the exact value of this counter, one possible solution involves instead using the following constructor:

function Employee (name, dept) {
   this.name = name || "";
   this.dept = dept || "general";
   if (name)
      this.id = idCounter++;
}

When you create an instance of Employee to use as a prototype, you do not supply arguments to the constructor. Using this definition of the constructor, when you do not supply arguments, the constructor does not assign a value to the id and does not update the counter. Therefore, for an Employee to get an assigned id, you must specify a name for the employee. In this example, mac.id would be 1.

No multiple inheritance

Some object-oriented languages allow multiple inheritance. That is, an object can inherit the properties and values from unrelated parent objects. JavaScript does not support multiple inheritance.

Inheritance of property values occurs at run time by JavaScript searching the prototype chain of an object to find a value. Because an object has a single associated prototype, JavaScript cannot dynamically inherit from more than one prototype chain.

In JavaScript, you can have a constructor function call more than one other constructor function within it. This gives the illusion of multiple inheritance. For example, consider the following statements:

function Hobbyist (hobby) {
   this.hobby = hobby || "scuba";
}

function Engineer (name, projs, mach, hobby) {
   this.base1 = WorkerBee;
   this.base1(name, "engineering", projs);
   this.base2 = Hobbyist;
   this.base2(hobby);
   this.machine = mach || "";
}
Engineer.prototype = new WorkerBee;

var dennis = new Engineer("Doe, Dennis", ["collabra"], "hugo")

Further assume that the definition of WorkerBee is as used earlier in this chapter. In this case, the dennis object has these properties:

dennis.name == "Doe, Dennis"
dennis.dept == "engineering"
dennis.projects == ["collabra"]
dennis.machine == "hugo"
dennis.hobby == "scuba"

So dennis does get the hobby property from the Hobbyist constructor. However, assume you then add a property to the Hobbyist constructor's prototype:

Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"]

The dennis object does not inherit this new property.

Метки документа и участники

 Внесли вклад в эту страницу: ndrsrv, NobbsNobby, Saviloff, makdeb, fscholz, esskia, ivan.p
 Обновлялась последний раз: ndrsrv,