【问题标题】:can somebody explain me how inheritance works in javascript有人可以解释一下继承在 javascript 中是如何工作的吗
【发布时间】:2014-10-07 12:00:38
【问题描述】:

谁能解释一下继承在javascript(JS)中的工作原理, 我已经阅读了许多教程,但我无法理解它所实现的目标.. 即使经过日夜没有结果..

我所经历的是:

console.log('Initialized..')

function Animal() {
    this.species = "animal";
}

Animal.prototype.category = function (){
    alert(this.species);
}

function Dog(){
    this.Animal();
}

copyPrototype(Dog, Animal)
var d = new Dog();
d.category();

来自http://www.sitepoint.com/javascript-inheritance/的参考教程

【问题讨论】:

  • 我会找到一个不同的教程。在此之前,你应该问问自己,你是否真的想做这种伪经典的类继承,以及为什么。
  • 嗨,谢谢,我是 js 新手,我是从设计背景开始的。我正在尝试学习 OOP 的工作原理。
  • @torazaburo 没有理由不学习 JavaScript 中的任何一种模式。不过,他是否应该使用它很重要。
  • 嗨@Icebox,我同意和不同意。没有任何人不应该学习它的理由,但可能有理由首先关注其他事情,而不是纠结于如何做类似 Java 的类层次结构。如果他正在学习一个框架,大多数人都会提供他们自己的类机器(这并不是说他在某些时候不应该学习引擎盖下发生的事情)。他还可以使用 CoffeeScript、TypeScript 或 ES6/Traceur 中的类,而不必担心诸如如何修补派生类的构造函数属性以确保 instanceof 正常工作等晦涩难懂的细节。

标签: javascript oop inheritance prototypal-inheritance


【解决方案1】:

在我看来,http://www.letscodejavascript.com/v3/episodes/lessons_learned/12 是了解我们在尝试让经典 OOP 在 JavaScript 中工作时滥用的机制的最佳资源。

当有人告诉我必须在 JS 中使用 OOP 时,我会这样做。这可能是我在网上某处捡到的东西。无论如何,这里是:

/// Make this script available somewhere
var extendsClass = this.extendsClass || function (d, b) {
    function __inheritedProto() { this.constructor = d; }
    __inheritedProto.prototype = b.prototype;
    d.prototype = new __inheritedProto();
}

var Animal = (function() {
    function Animal(data) {
        this.value = data;
    }
    Animal.prototype.method = function() {
        return this.value;
    };
    return Animal;
})();

var Dog = (function(_super) {
    extendsClass(Dog, _super);
    function Dog() {
        _super.apply(this, arguments);
    }
    Dog.prototype.method2 = function() {
        return this.value * 2; //do something else
    };
    return Dog;
})(Animal);

/// Create some instances
var animal = new Animal(1);
var dog = new Dog(2);


/// Call some methods
animal.method();  // 1
dog.method(); // 2
dog.method2();// 4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-03
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多