Performing inheritance in JavaScript

Они - полностью несвязанные вещи. Думайте об управлении версиями как своего рода "машина времени", которую можно использовать для движения назад и вперед вовремя с кодом.

19
задан Peter Mortensen 14 February 2013 в 21:13
поделиться

2 ответа

The JavaScript object oriented paradigm is prototype based. There are no "classes", just objects.

You can implement inheritance in different ways. The two more popular alternatives are the "pseudo-classical" and the "prototypal" forms. For example:

Pseudo-classical inheritance

I think this is the most popular way. You create constructor functions that you use with the new operator, and you add members through the constructor function prototype.

// Define the Person constructor function
function Person() {}

Person.prototype.sayHello = function(){
    alert ('hello');
};

// Define the Student constructor function
function Student() {}

// Inherit from Person
Student.prototype = new Person();

// Correct the constructor pointer, because it points to Person
Student.prototype.constructor = Student;

// Replace the sayHello method (a polymorphism example)
Student.prototype.sayHello = function () {
    alert('hi, I am a student');
}

var student1 = new Student();
student1.sayHello();

Prototypal inheritance

Basically we make a helper function that takes an object as a parameter and returns an empty new object that inherits from the old one, objects inherit from objects.

// Helper function
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

var person = {
    sayHello : function () {
        alert('Person object');
    },
    walk : function () {
        alert('walk');
    }
};

var student1 = Object.create(person);
student1.sayHello = function () {
    alert('hello I am a student');
};

Another interesting form is the parasitic inheritance. In the "derived" constructor you create a "base" object instance. That object is augmented and that new instance is returned:

// Person constructor function
function Person(name) {
    this.name = name;
}

function Student(value) {
    var that = new Person(value);
    that.sayHello = function () {
        alert('hello I am a student');
    };
    return that;
}
48
ответ дан 30 November 2019 в 02:27
поделиться

JavaScript inheritance is done through prototypes. You do not define anything with a class keyword, but you make a function that's used as a constructor to build new objects (with the new keyword ).

function person(name) {
    this.name = name;
}

person.prototype.getName = function() {
    return this.name;
}

var john = new person('john');
alert( john.getName() );

You can access this prototypal method with:

person.prototype.getName

All newly created objects are constructed based on the core constructors (sometimes called classes by people coming from classical inheritance languages, or the core objects) such as Object, so every object in JavaScript has access to Object.prototype. If you were to make a custom method for all objects you would do:

Object.prototype.foo = function(){};
alert( typeof ({}).foo ) // 'function'

Key notes:

  • The this word is used to refer to the current object, so this.name sets the name property of the object being created when new person is invoked.
  • You can define new prototypal methods on the constructor with constructorName.prototype.nameOfMethod = function(){} after you define the constructor. You do not need to define it inside of the constructor, and it's more efficient this way.
  • Unless you explicitly define properties on the object, so with the john object I made, since there is no getName method directly attached to the john object, the interpreter needs to travel up to the prototype of the john object, which is the person.prototype and access the method from there. You can use hasOwnProperty to see if an object directly owns a property or not.

Reference:

3
ответ дан 30 November 2019 в 02:27
поделиться
Другие вопросы по тегам:

Похожие вопросы: