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

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

问题描述

现在,我知道你不能像C#那样执行继承,我已经看到它在互联网上提到它是有可能的。如果不可能使用纯粹的JavaScript代码,那么是否可以使用 Ext JS 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:

我认为这是最受欢迎的方式。您可以使用与构造函数 ://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/new_Operatorrel =noreferrer> 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天全站免登陆