在 JavaScript 中执行继承 [英] Performing inheritance in JavaScript

查看:18
本文介绍了在 JavaScript 中执行继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在虽然我知道您不能像在 C# 中那样执行继承,但我在 Internet 上看到它提到它是可能的.如果无法使用纯 JavaScript 代码,那么是否可以使用 Ext JS 以及如何使用?

Now while I know that you can not perform inheritance like you would in C#, I have seen it mentioned on the Internet that it is kind of possible. If it's not possible using plain JavaScript code then would it be possible using Ext JS and if so how?

推荐答案

JavaScript 面向对象的范式是 基于原型.没有类",只有对象.

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:

我认为这是最流行的方式.您创建构造函数,用于new 操作符,你通过构造函数原型添加成员.

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();

原型继承

基本上我们创建了一个辅助函数,它将一个对象作为参数并返回一个从旧对象继承的空新对象,对象从对象继承.

// 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;
}

这篇关于在 JavaScript 中执行继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆