javascript - 好的伪经典 JavaScript 继承模式?

标签 javascript inheritance prototypal-inheritance

阅读 Crocksford 的《Javascript The good Parts》后,我一直在寻求编写一些高效、可读且可重用的 JavaScript 代码。 这就是我的目标,尤其是对象的属性是公开的。

话虽如此,这段代码是否有任何特定的问题或改进点?

( function(){

    window.App = {}

    // define uma pessoa normal
    App.Person = function(name){
        this.name = name || "anon"
        this.iq = 100
        this.fortune_number = Math.floor(Math.random()*100)
    }

    App.Person.prototype.sayName = function() {
        return (this.name+"!")
    }

    App.Person.prototype.sayIQ = function() {
        return (this.iq)
    }



    // define um genio da humanidade
    App.Genius = function(name) {
        App.Person.call( this, name )
        this.iq = 9000
    };
    // inherits All methods from Pessoa
    App.Genius.prototype = App.Person.prototype

    App.Genius.prototype.solveNP = function() {
        return "eureka!"
    };

})()


var p = new App.Person('Jon')
console.log( "A Person:", p.sayName(), p.fortune_number, p.sayIQ() )
//-> A Person: Jon! 10 100

var g = new App.Genius( 'Eugenios' )
console.log( "A Genious:", g.sayName(), g.fortune_number, g.sayIQ(), g.solveNP() )
//-> A Genious: Eugenios! 7 9000 eureka!

我特别不确定这一行是否 App.Genius.prototype = App.Person.prototype很好,因为我通常会在一些新实例之后看到原型(prototype)设计,例如Mozilla Guide

最佳答案

您的代码中没有真正的继承。您必须扩展原型(prototype)链才能拥有真正的(原型(prototype))继承。

// This is how it's done in JS
Child.prototype = new Parent();
Child.prototype.constructor = Child;

这会产生执行父构造函数的副作用,这在某些情况下可能会很糟糕(例如,如果构造函数需要任何参数)。您应该使用以下位来进行继承。

var Fn = function () {}; // empty constructor, no side-effects
Fn.prototype = Parent.prototype;

Child.prototype = new Fn();
Child.prototype.constructor = Child;

关于javascript - 好的伪经典 JavaScript 继承模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8188259/

相关文章:

javascript - ES5 中的 Object.defineProperty?

javascript继承同时节省内存

javascript - 通过 css/javascript 对 Angular 图像叠加

javascript - js获取构造函数名称链

c++ - 在虚拟继承的情况下如何对待祖 parent 类的成员?

C++:访问父方法和变量

javascript - 尝试在 document.ready 中使用 jQuery 在 Bigcommerce Classic Next 主题中触发对产品选项的点击

javascript - 想要显示前三个 div,然后让剩余部分切换

javascript - 更改对话框的灰色

JavaScript - 继承错误