Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 子类不';t继承超类属性_Javascript_Oop_Inheritance - Fatal编程技术网

Javascript 子类不';t继承超类属性

Javascript 子类不';t继承超类属性,javascript,oop,inheritance,Javascript,Oop,Inheritance,在定义子类时,我得到了构造函数参数的typerorr:undefined,正如我看到的,它充当占位符。到底发生了什么以及如何解决 function Class(object) { this.name = object.name; } var myClass = new Class({ name: "ClassName" }) console.log(myClass.name); function SubClass(object) { this.name = obj

在定义子类时,我得到了构造函数参数的typerorr:undefined,正如我看到的,它充当占位符。到底发生了什么以及如何解决

function Class(object) {
    this.name = object.name;
}

var myClass = new Class({
    name: "ClassName"
})

console.log(myClass.name); 

function SubClass(object) {
    this.name = object.name;
}

SubClass.prototype = new Class();
SubClass.prototype.constructor = SubClass;

var mySubClass = new SubClass({
    name: "SubClassName"
})

//TypeError:对象未定义

通常,基类的原型上会有方法,因此更适合使用
SubClass.prototype=object.create(BaseClass.prototype)
,还可以在基类的构造函数中调用父构造函数,以便在父构造函数中找到
对象.name
(这是由于未向
子类.prototype=new class()传递任何内容而导致的错误)

这里有一些有用的参考资料


通常,基类的原型上会有方法,因此更适合使用
SubClass.prototype=Object.create(BaseClass.prototype)
,并在基类的构造函数中调用父构造函数,以便在父构造函数中找到
Object.name
(这是由于未将任何内容传递到
SubClass.prototype=new Class()
中而导致的错误

这里有一些有用的参考资料


通常,基类的原型上会有方法,因此更适合使用
SubClass.prototype=Object.create(BaseClass.prototype)
,并在基类的构造函数中调用父构造函数,以便在父构造函数中找到
Object.name
(这是由于未将任何内容传递到
SubClass.prototype=new Class()
中而导致的错误

这里有一些有用的参考资料


通常,基类的原型上会有方法,因此更适合使用
SubClass.prototype=Object.create(BaseClass.prototype)
,并在基类的构造函数中调用父构造函数,以便在父构造函数中找到
Object.name
(这是由于未将任何内容传递到
SubClass.prototype=new Class()
中而导致的错误

这里有一些有用的参考资料


  • 有一个打字错误:
    子类。原型
    代替
    子类。原型
    有一个打字错误:
    子类。原型
    代替
    子类。原型
    有一个打字错误:
    子类。原型
    代替
    子类。原型
    有一个打字错误:
    子类。原型
    代替
    子类.原型
    function Class(object) {
        this.name = object.name;
    }
    
    Class.prototype.sayName = function () {
        return this.name;
    }
    
    var myClass = new Class({
        name: "ClassName"
    });
    
    console.log(myClass.name); 
    
    function SubClass(object) {
        // call parent constructor with context of the new SubClass instance
        Class.call(this, object);
    }
    
    SubClass.prototype = Object.create(Class.prototype);
    SubClass.prototype.constructor = SubClass;
    
    var mySubClass = new SubClass({
        name: "SubClassName"
    });
    
    console.log(mySubClass.sayName());
    // > "SubClassName"