如何从javascript中的类继承?


99

在PHP / Java中,可以做到:

class Sub extends Base
{
}

并且,Super类的所有公共/受保护的方法,属性,字段等都会自动成为Sub类的一部分,如有必要,可以重写这些类。

Javascript中的等效功能是什么?





那克罗克福德方式仍然有效吗?ZParenizor.inherits(Parenizor);
罗兰·希奇波尼亚

Answers:


80

我已经更改了现在的操作方式,我尝试避免使用构造函数和它们的prototype属性,但是我从2010年开始的旧答案仍在底部。我现在更喜欢Object.create()Object.create适用于所有现代浏览器。

我应该注意到,这Object.create通常比使用函数构造函数得多new

//The prototype is just an object when you use `Object.create()`
var Base = {};

//This is how you create an instance:
var baseInstance = Object.create(Base);

//If you want to inherit from "Base":
var subInstance = Object.create(Object.create(Base));

//Detect if subInstance is an instance of Base:
console.log(Base.isPrototypeOf(subInstance)); //True

jsfiddle

使用Object.create的最大好处之一是能够传递defineProperties参数,该参数使您可以有效控制如何访问和枚举类的属性,并且我还使用函数来创建实例,这些函数可以用作构造函数,因为您可以在最后进行初始化,而不仅仅是返回实例。

var Base = {};

function createBase() {
  return Object.create(Base, {
    doSomething: {
       value: function () {
         console.log("Doing something");
       },
    },
  });
}

var Sub = createBase();

function createSub() {
  return Object.create(Sub, {
    doSomethingElse: {
      value: function () {
        console.log("Doing something else");
      },
    },
  }); 
}

var subInstance = createSub();
subInstance.doSomething(); //Logs "Doing something"
subInstance.doSomethingElse(); //Logs "Doing something else"
console.log(Base.isPrototypeOf(subInstance)); //Logs "true"
console.log(Sub.isPrototypeOf(subInstance)); //Logs "true

jsfiddle

这是我2010年的原始答案:

function Base ( ) {
  this.color = "blue";
}

function Sub ( ) {

}
Sub.prototype = new Base( );
Sub.prototype.showColor = function ( ) {
 console.log( this.color );
}

var instance = new Sub ( );
instance.showColor( ); //"blue"

5
sub.prototype.constructor值怎么样?我认为也应该将其设置为子值。
maximus

除了您使用保留关键字(“ super”)作为类名之外,我无法运行您的示例:jsbin.com/ixiyet/8/edit
MOnsDaR 2013年

@MOnsDaR我将其重命名为Base
Bjorn

如果我alert()过去看到什么instance.showColor()回报,我仍然会得到undefinedjsbin.com/uqalin/1
MOnsDaR 2013年

1
@MOnsDaR是因为它控制台记录日志,它不返回任何要显示的警报。您是否在showColor中看到return语句?
比约恩

190

在JavaScript中,您没有类,但是可以通过许多方式来继承和重用行为:

伪经典继承(通过原型):

function Super () {
  this.member1 = 'superMember1';
}
Super.prototype.member2 = 'superMember2';

function Sub() {
  this.member3 = 'subMember3';
  //...
}
Sub.prototype = new Super();

应与new操作员一起使用:

var subInstance = new Sub();

函数应用程序或“构造函数链接”:

function Super () {
  this.member1 = 'superMember1';
  this.member2 = 'superMember2';
}


function Sub() {
  Super.apply(this, arguments);
  this.member3 = 'subMember3';
}

此方法也应与new运算符一起使用:

var subInstance = new Sub();

与第一个示例的不同之处在于,当我们applySuper构造函数添加到this对象内部时Sub,它会直接在新实例this上添加分配给on 的属性Super,例如,subInstance包含属性member1member2直接(subInstance.hasOwnProperty('member1') == true;)。

在第一个示例中,这些属性是通过原型链实现的,它们存在于内部[[Prototype]]对象上。

寄生继承或功率构造函数:

function createSuper() {
  var obj = {
    member1: 'superMember1',
    member2: 'superMember2'
  };

  return obj;
}

function createSub() {
  var obj = createSuper();
  obj.member3 = 'subMember3';
  return obj;
}

这种方法基本上基于“对象扩充”,您不需要使用new运算符,并且您可以看到,this不涉及关键字。

var subInstance = createSub();

ECMAScript第5版。Object.create方法:

// Check if native implementation available
if (typeof Object.create !== 'function') {
  Object.create = function (o) {
    function F() {}  // empty constructor
    F.prototype = o; // set base object as prototype
    return new F();  // return empty object with right [[Prototype]]
  };
}

var superInstance = {
  member1: 'superMember1',
  member2: 'superMember2'
};

var subInstance = Object.create(superInstance);
subInstance.member3 = 'subMember3';

上述方法是Crockford提出的原型继承技术。

对象实例继承自其他对象实例,仅此而已。

这种技术可以比简单的“对象增强”更好,因为继承属性不通过所有复制的新的对象的情况下,由于基体对象被设定为[[Prototype]]所述的扩展的目的,在上面的例子中subInstance物理上只包含member3属性。


3
不要使用实例进行继承-使用ES5 Object.create()或自定义clone()函数(例如 mercurial.intuxication.org/hg/js-hacks/raw-file/tip/clone.js)直接从原型对象继承;看评论stackoverflow.com/questions/1404559/...一个解释
克里斯托夫

感谢@Christoph,我正要提到该Object.create方法:)
CMS 2010年

1
这是不正确的继承,因为您将在Sub的原型上拥有Super的实例成员。因此,Sub的所有实例将共享相同的member1变量,这是完全不希望的。他们当然可以重写它,但这根本没有意义。 github.com/dotnetwise/Javascript-FastClass是更好的糖解决方案。
Adaptabi

您好@CMS,您能否解释一下,为什么我需要在第一个示例中创建父类的实例来设置子类的继承?我说的是这一行:Sub.prototype = new Super();。如果在脚本执行期间永远不会使用这两个类怎么办?看起来像是性能问题。如果未实际使用子类,为什么需要创建父类?你能详细说明一下吗?这是问题的简单演示:jsfiddle.net/slavafomin/ZeVL2谢谢!
Slava Fomin II

在所有示例(最后一个示例除外)中,都有一个用于Super的“类”和一个用于Sub的“类”,然后创建Sub的实例。您可以为Object.create示例添加一个可比较的示例吗?
路加福音

49

对于那些在2019年或之后到达此页面的人

在最新版本的ECMAScript标准(ES6)中,可以使用关键字class

注意类的定义不是常规的object; 因此,班级成员之间没有逗号。要创建类的实例,必须使用new关键字。要从基类继承,请使用extends

class Vehicle {
   constructor(name) {
      this.name = name;
      this.kind = 'vehicle';
   }
   getName() {
      return this.name;
   }   
}

// Create an instance
var myVehicle = new Vehicle('rocky');
myVehicle.getName(); // => 'rocky'

要从基类继承,请使用extends

class Car extends Vehicle {
   constructor(name) {
      super(name);
      this.kind = 'car'
   }
}

var myCar = new Car('bumpy');

myCar.getName(); // => 'bumpy'
myCar instanceof Car; // => true
myCar instanceof Vehicle; // => true

在派生类中,可以从任何构造函数或方法中使用super来访问其基类:

  • 要调用父构造函数,请使用 super().
  • 要呼叫其他成员,请使用super.getName()

使用类还有更多。如果您想更深入地研究该主题,我建议您使用Axel Rauschmayer博士的“ ECMAScript 6中的类 ”。

资源


1
在引擎盖下,class并且extends对于原型链来说是(非常有用的)语法糖:stackoverflow.com/a/23877420/895245
Ciro Santilli郝海东冠状病六四事件法轮功

仅作为参考信息“ instance.name”,此处“ mycar.name”将返回该类的名称。这是ES6和ESnext的默认行为。在这里,mycar.name将返回“ Vehicle”
Shiljo Paulson,

7

嗯,在JavaScript中没有“类继承”,只有“原型继承”。因此,您无需创建“卡车”类,然后将其标记为“汽车”的子类。取而代之的是,您创建一个对象“ Jack”,并说它使用“ John”作为原型。如果约翰知道“ 4 + 4”是多少,那么杰克也知道。

我建议您在这里阅读Douglas Crockford的有关原型继承的文章:http : //javascript.crockford.com/prototypal.html他还展示了如何使JavaScript具有与其他OO语言一样的“外观相似”继承,然后对此进行了解释。实际上意味着以一种不被使用的方式破坏javaScript。


假设杰克的原型是约翰。在运行时,我向John添加了一个属性/行为。我会从杰克那里得到财产/行为吗?
Ram Bavireddi

你一定会的。例如,这就是人们通常向所有字符串对象(不是内置的)添加“ trim()”方法的方式,请参见此处的示例:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ …
naivists,2015年

6

我发现这句话最有启发性:

本质上,JavaScript “类”只是一个Function对象,它充当构造函数以及附加的原型对象。(资料来源:大师卡兹

我喜欢使用构造函数而不是对象,因此我偏爱CMS此处介绍的“伪经典继承”方法。这是带有原型链多重继承的示例:

// Lifeform "Class" (Constructor function, No prototype)
function Lifeform () {
    this.isLifeform = true;
}

// Animal "Class" (Constructor function + prototype for inheritance)
function Animal () {
    this.isAnimal = true;
}
Animal.prototype = new Lifeform();

// Mammal "Class" (Constructor function + prototype for inheritance)
function Mammal () {
    this.isMammal = true;
}
Mammal.prototype = new Animal();

// Cat "Class" (Constructor function + prototype for inheritance)
function Cat (species) {
    this.isCat = true;
    this.species = species
}
Cat.prototype = new Mammal();

// Make an instance object of the Cat "Class"
var tiger = new Cat("tiger");

console.log(tiger);
// The console outputs a Cat object with all the properties from all "classes"

console.log(tiger.isCat, tiger.isMammal, tiger.isAnimal, tiger.isLifeform);
// Outputs: true true true true

// You can see that all of these "is" properties are available in this object
// We can check to see which properties are really part of the instance object
console.log( "tiger hasOwnProperty: "
    ,tiger.hasOwnProperty("isLifeform") // false
    ,tiger.hasOwnProperty("isAnimal")   // false
    ,tiger.hasOwnProperty("isMammal")   // false
    ,tiger.hasOwnProperty("isCat")      // true
);

// New properties can be added to the prototypes of any
// of the "classes" above and they will be usable by the instance
Lifeform.prototype.A    = 1;
Animal.prototype.B      = 2;
Mammal.prototype.C      = 3;
Cat.prototype.D         = 4;

console.log(tiger.A, tiger.B, tiger.C, tiger.D);
// Console outputs: 1 2 3 4

// Look at the instance object again
console.log(tiger);
// You'll see it now has the "D" property
// The others are accessible but not visible (console issue?)
// In the Chrome console you should be able to drill down the __proto__ chain
// You can also look down the proto chain with Object.getPrototypeOf
// (Equivalent to tiger.__proto__)
console.log( Object.getPrototypeOf(tiger) );  // Mammal 
console.log( Object.getPrototypeOf(Object.getPrototypeOf(tiger)) ); // Animal
// Etc. to get to Lifeform

这是MDN的另一个很好的资源,这是一个jsfiddle,因此您可以尝试一下


4

Javascript继承与Java和PHP有所不同,因为它实际上没有类。相反,它具有提供方法和成员变量的原型对象。您可以链接这些原型以提供对象继承。我在研究此问题时发现的最常见模式在Mozilla开发人员网络上进行了描述。我已经更新了他们的示例,以包括对超类方法的调用,并在警报消息中显示日志:

// Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

// superclass method
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  log += 'Shape moved.\n';
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

// Override method
Rectangle.prototype.move = function(x, y) {
  Shape.prototype.move.call(this, x, y); // call superclass method
  log += 'Rectangle moved.\n';
}

var log = "";
var rect = new Rectangle();

log += ('Is rect an instance of Rectangle? ' + (rect instanceof Rectangle) + '\n'); // true
log += ('Is rect an instance of Shape? ' + (rect instanceof Shape) + '\n'); // true
rect.move(1, 1); // Outputs, 'Shape moved.'
alert(log);

就个人而言,我发现Java语言中的继承很尴尬,但这是我发现的最佳版本。


3

(古典意义上的)你不能。Javascript是一种原型语言。您会发现,您永远不会在Javascript中声明“类”。您仅定义对象的状态和方法。要产生继承,您需要获取一些对象并将其原型化。原型扩展了新功能。


1

您可以使用.inheritWith.fastClass 。它比大多数流行的库都快,有时甚至比本机版本还快。

非常容易使用:

function Super() {
   this.member1 = "superMember";//instance member
}.define({ //define methods on Super's prototype
   method1: function() { console.log('super'); } //prototype member
}.defineStatic({ //define static methods directly on Super function 
   staticMethod1: function() { console.log('static method on Super'); }
});

var Sub = Super.inheritWith(function(base, baseCtor) {
   return {
      constructor: function() {//the Sub constructor that will be returned to variable Sub
         this.member3 = 'subMember3'; //instance member on Sub
         baseCtor.apply(this, arguments);//call base construcor and passing all incoming arguments
      },
      method1: function() { 
         console.log('sub'); 
         base.method1.apply(this, arguments); //call the base class' method1 function
      }
}

用法

var s = new Sub();
s.method1(); //prints:
//sub 
//super

1
function Person(attr){
  this.name = (attr && attr.name)? attr.name : undefined;
  this.birthYear = (attr && attr.birthYear)? attr.birthYear : undefined;

  this.printName = function(){
    console.log(this.name);
  }
  this.printBirthYear = function(){
    console.log(this.birthYear);
  }
  this.print = function(){
    console.log(this.name + '(' +this.birthYear+ ')');
  }
}

function PersonExt(attr){
  Person.call(this, attr);

  this.print = function(){
    console.log(this.name+ '-' + this.birthYear);
  }
  this.newPrint = function(){
    console.log('New method');
  }
}
PersonExt.prototype = new Person();

// Init object and call methods
var p = new Person({name: 'Mr. A', birthYear: 2007});
// Parent method
p.print() // Mr. A(2007)
p.printName() // Mr. A

var pExt = new PersonExt({name: 'Mr. A', birthYear: 2007});
// Overwriten method
pExt.print() // Mr. A-2007
// Extended method
pExt.newPrint() // New method
// Parent method
pExt.printName() // Mr. A

1

看了很多文章之后,我想出了这个解决方案(jsfiddle在这里)。大多数时候,我不需要更复杂的东西

var Class = function(definition) {
    var base = definition.extend || null;
    var construct = definition.construct || definition.extend || function() {};

    var newClass = function() { 
        this._base_ = base;        
        construct.apply(this, arguments);
    }

    if (definition.name) 
        newClass._name_ = definition.name;

    if (definition.extend) {
        var f = function() {}       
        f.prototype = definition.extend.prototype;      
        newClass.prototype = new f();   
        newClass.prototype.constructor = newClass;
        newClass._extend_ = definition.extend;      
        newClass._base_ = definition.extend.prototype;         
    }

    if (definition.statics) 
        for (var n in definition.statics) newClass[n] = definition.statics[n];          

    if (definition.members) 
        for (var n in definition.members) newClass.prototype[n] = definition.members[n];    

    return newClass;
}


var Animal = Class({

    construct: function() {        
    },

    members: {

        speak: function() {
            console.log("nuf said");                        
        },

        isA: function() {        
            return "animal";           
        }        
    }
});


var Dog = Class({  extend: Animal,

    construct: function(name) {  
        this._base_();        
        this.name = name;
    },

    statics: {
        Home: "House",
        Food: "Meat",
        Speak: "Barks"
    },

    members: {
        name: "",

        speak: function() {
            console.log( "ouaf !");         
        },

        isA: function(advice) {
           return advice + " dog -> " + Dog._base_.isA.call(this);           
        }        
    }
});


var Yorkshire = Class({ extend: Dog,

    construct: function(name,gender) {
        this._base_(name);      
        this.gender = gender;
    },

    members: {
        speak: function() {
            console.log( "ouin !");           
        },

        isA: function(advice) {         
           return "yorkshire -> " + Yorkshire._base_.isA.call(this,advice);       
        }        
    }
});


var Bulldog = function() { return _class_ = Class({ extend: Dog,

    construct: function(name) {
        this._base_(name);      
    },

    members: {
        speak: function() {
            console.log( "OUAF !");           
        },

        isA: function(advice) {         
           return "bulldog -> " + _class_._base_.isA.call(this,advice);       
        }        
    }
})}();


var animal = new Animal("Maciste");
console.log(animal.isA());
animal.speak();

var dog = new Dog("Sultan");
console.log(dog.isA("good"));
dog.speak();

var yorkshire = new Yorkshire("Golgoth","Male");
console.log(yorkshire.isA("bad"));
yorkshire.speak();

var bulldog = new Bulldog("Mike");
console.log(bulldog.isA("nice"));
bulldog.speak();

1

多亏了CMS的回答,并且在对原型和Object.create进行了一段时间的修改之后,我得以使用apply提出了一个很好的继承解决方案,如下所示:

var myNamespace = myNamespace || (function() {
    return {

        BaseClass: function(){
            this.someBaseProperty = "someBaseProperty";
            this.someProperty = "BaseClass";
            this.someFunc = null;
        },

        DerivedClass:function(someFunc){
            myNamespace.BaseClass.apply(this, arguments);
            this.someFunc = someFunc;
            this.someProperty = "DerivedClass";
        },

        MoreDerivedClass:function(someFunc){
            myNamespace.DerivedClass.apply(this, arguments);
            this.someFunc = someFunc;
            this.someProperty = "MoreDerivedClass";
        }
    };
})();


1
function Base() {
    this.doSomething = function () {
    }
}

function Sub() {
    Base.call(this); // inherit Base's method(s) to this instance of Sub
}

var sub = new Sub();
sub.doSomething();

2
请不要仅仅发布代码,解释它的功能以及它如何回答问题。
Patrick Hund

1

ES6课程:

Javascript没有类。javascript中的类仅仅是基于javascript 原型继承模式的语法糖。您可以使用JS class来强制执行原型继承,但重要的是要意识到您实际上仍在使用内部构造函数。

当您es6使用extends关键字从“类” 扩展时,这些概念也适用。这只是在原型链中创建了一个附加链接。的__proto__

例:

class Animal {
  makeSound () {
    console.log('animalSound');
  }
}

class Dog extends Animal {
   makeSound () {
    console.log('Woof');
  }
}


console.log(typeof Dog)  // classes in JS are just constructor functions under the hood

const dog = new Dog();

console.log(dog.__proto__ === Dog.prototype);   
// First link in the prototype chain is Dog.prototype

console.log(dog.__proto__.__proto__ === Animal.prototype);  
// Second link in the prototype chain is Animal.prototype
// The extends keyword places Animal in the prototype chain
// Now Dog 'inherits' the makeSound property from Animal

Object.create()

Object.create()这也是在javascript中的JS中创建继承的方法。Object.create()是创建新对象的函数,将现有对象作为参数。它将把作为参数接收的对象分配给__proto__新创建的对象的属性。再次重要的是要意识到我们必须绑定到JS所体现的原型继承范式。

例:

const Dog = {
  fluffy: true,
  bark: () => {
      console.log('woof im a relatively cute dog or something else??');
  }
};

const dog = Object.create(Dog);

dog.bark();


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.