Javascript继承;电话和原型 [英] Javascript Inheritance ; call and prototype

查看:86
本文介绍了Javascript继承;电话和原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在Javascript中实现继承,通常会执行以下两个步骤;

To implement inheritance in Javascript, one generally does the following 2 steps;

假设我有一个基类Animal

Say I have a base class "Animal"

var Animal = function(name){
this.name = name;
}

我现在想从同一个派生出一个子类Dog。所以我会说

I now want to derive a sub class "Dog" from the same. So I would say

var Dog = function(name) {
   Animal.call(this,name);
}

所以我从派生类构造函数中调用我的父类构造函数。
第二步是设置原型如下;

So I am calling my parent class constructor from my derived class constructor. The 2nd step is to set the prototype as follows;

Dog.prototype = new Animal();

现在,我可以从派生类Dog中访问任何基本的Animal类属性。

Now I can access any of the base "Animal" class properties from within my derived class Dog.

所以我的问题是为什么这两个步骤是必要的?
如果我们只是使用

So my question is why are these 2 steps necessary ? If we just call the base class constructor using

Animal.call(this,name);

还不足以实现继承吗?

为什么我们需要使用设置原型属性Dog.prototype = new Animal();

我想了解上述两个步骤的作用是什么?

I wanted to understand what each of the above 2 steps does ?

推荐答案

第一件事要理解的是,在JavaScript中没有经典的继承,我们从C语言中知道的机制,如Java,C#等堡垒。在JavaScript中,可以使用原型继承来完成代码重用。我们唯一拥有的是对象,代码块,它们还活着并且不需要实例化。例如:当在对象上调用函数时 - 就像方法一样,检查当前对象是否已知函数。如果没有找到,引擎会调用它原型(这是另一个对象)并检查函数名是否已知且可以调用。没有找到时,会调用原型等等。因此,设置对象的原型可以编排原型链。

The first thing to understand is that in JavaScript there is no classical inheritance, the mechanism we know from C-languages like Java, C# and so fort. In JavaScript, code reuse can be accomplished by using prototypal-inheritance. The only thing we have is objects, blocks of code who are alive and don't need to be instantiated. For example: when a function is invoked on an object - like a method, the current object is inspected whether the function is known. If not found, the engine calls it prototype (which is an other object) and inspects whether the function name is known and can be invoked. When not found, íts prototype is called and so on. So, setting the prototype of a object one can orchestrate the prototype-chain.

回答你的问题:没有必要,它取决于你想要的。代码重用是您想要的,继承是您实现这一目标的方式(Stoyan Stefanov - JavaScript Patterns)。在JavaScript中,有更多的方法可以重用代码。

To answer your question: nothing is necessary, its up to you what you want. Code reuse is what you want and inheritance is the way you can achieve this (Stoyan Stefanov - JavaScript Patterns). In JavaScript, more ways are available to reuse code.

此外,这绑定到当前上下文,并不总是当前对象。

Furthermore, this is bound to the current context, not always the current object.

这篇关于Javascript继承;电话和原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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