在PHP / Java中,可以做到:
class Sub extends Base
{
}
并且,Super类的所有公共/受保护的方法,属性,字段等都会自动成为Sub类的一部分,如有必要,可以重写这些类。
Javascript中的等效功能是什么?
在PHP / Java中,可以做到:
class Sub extends Base
{
}
并且,Super类的所有公共/受保护的方法,属性,字段等都会自动成为Sub类的一部分,如有必要,可以重写这些类。
Javascript中的等效功能是什么?
Answers:
我已经更改了现在的操作方式,我尝试避免使用构造函数和它们的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
使用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
这是我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"
在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();
与第一个示例的不同之处在于,当我们apply
将Super
构造函数添加到this
对象内部时Sub
,它会直接在新实例this
上添加分配给on 的属性Super
,例如,subInstance
包含属性member1
并member2
直接(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
属性。
Object.create()
或自定义clone()
函数(例如 mercurial.intuxication.org/hg/js-hacks/raw-file/tip/clone.js)直接从原型对象继承;看评论stackoverflow.com/questions/1404559/...一个解释
Object.create
方法:)
member1
变量,这是完全不希望的。他们当然可以重写它,但这根本没有意义。 github.com/dotnetwise/Javascript-FastClass是更好的糖解决方案。
Sub.prototype = new Super();
。如果在脚本执行期间永远不会使用这两个类怎么办?看起来像是性能问题。如果未实际使用子类,为什么需要创建父类?你能详细说明一下吗?这是问题的简单演示:jsfiddle.net/slavafomin/ZeVL2谢谢!
在最新版本的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中的类 ”。
嗯,在JavaScript中没有“类继承”,只有“原型继承”。因此,您无需创建“卡车”类,然后将其标记为“汽车”的子类。取而代之的是,您创建一个对象“ Jack”,并说它使用“ John”作为原型。如果约翰知道“ 4 + 4”是多少,那么杰克也知道。
我建议您在这里阅读Douglas Crockford的有关原型继承的文章:http : //javascript.crockford.com/prototypal.html他还展示了如何使JavaScript具有与其他OO语言一样的“外观相似”继承,然后对此进行了解释。实际上意味着以一种不被使用的方式破坏javaScript。
我发现这句话最有启发性:
本质上,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
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语言中的继承很尴尬,但这是我发现的最佳版本。
您可以使用.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
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
看了很多文章之后,我想出了这个解决方案(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();
多亏了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";
}
};
})();
从ES2015开始,这就是在JavaScript中进行继承的方式
class Sub extends Base {
}
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();
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()
这也是在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();