javascript - 为什么子对象没有使用模块模式的父方法?

标签 javascript

Parent = (function() {
    var parent = function(name) {
        this.name = name;
    };

    parent.prototype.dostuff = function() {
      console.log(this.name);  
    };

    parent.prototype.more = function() {
      console.log("this should be available on both ... " + this.name);  
    };

    return parent;
}());

Child = (function() {
    var child = function(name) {
        Parent.call(this, name);
        this.prototype = Object.create(Parent.prototype);
    };

    child.prototype.dostuff = function() {
      console.log("the child class ... " + this.name);
    };

    child.prototype.special = function() {
      console.log("only the child has this method");
    };

    return child;
}());

在上面我的父对象有一个名为“more”的方法,但是当我像这样新建子对象时..我无法调用more方法,除非我手动原型(prototype)化它。上面我缺少什么可以让我免费获得原型(prototype)方法?

var first = new Parent("father");
var last = new Child("son");

使用 jsfiddle 进行更新

http://jsfiddle.net/kz7Xk/

最佳答案

您在实例上设置原型(prototype),您应该在函数本身上设置它。

当使用new创建对象时,构造函数中的

this指的是对象本身。但原型(prototype)是用作构造函数的函数的属性,而不是实例的属性。

所以你想要这样的东西:

Child = (function() {
    var child = function(name) {
        Parent.call(this, name);
    };

    child.prototype = Object.create(Parent.prototype);

    child.prototype.dostuff = function() {
      console.log("the child class ... " + this.name);
    };

    child.prototype.special = function() {
      console.log("only the child has this method");
    };

    return child;
}());

Child的原型(prototype)被设置为一个新对象,其原型(prototype)上有parent的原型(prototype),允许它继承一切。

关于javascript - 为什么子对象没有使用模块模式的父方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16329160/

相关文章:

javascript - AEM 6.3 : Sling Servlet registered with resourceType

javascript - 瓦坎达-基本了解

javascript - Firebase/Ionic4 上传和裁剪图片到存储

javascript - 如何正确删除多个事件监听器?

javascript - 在页面底部设置多个div元素为 "position: fixed"

Javascript 基本算法

javascript - Django ;在自定义小部件中向媒体文件添加变量

javascript - D3Js 树布局自动缩放功能

javascript - 当 Maxitem = 1 时,是否可以防止 Selectize 转换为下拉列表?

javascript - __doPostBack 在 safari 或 firefox 中不起作用,在 IE 中起作用