繁体   English   中英

无法访问对象原型上的方法

[英]Can't access methods on object's prototype

我可以创建一个Cat对象并在其原型上设置一个方法来打印出猫的名字。

 var log = function(message) { var results = $('#result'); results.append('<p>' + message + '</p>'); }; function Cat(name) { this.name = name; } Cat.prototype.speak = function() { log('My name is ' + this.name); }; var fluffy = new Cat('Fluffy'); var tiddles = new Cat('Tiddles'); log(fluffy.name); fluffy.speak(); log(tiddles.name); tiddles.speak(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="result"></div> 

但是,当我尝试将猫的原型设置为动物时,我无法访问speak方法:

function Animal(name, sound) {
    this.name = name;
    this.sound = sound;

    this.speak = function() {
        log(sound + '! My name is ' + name);
    };
}

function Cat(name) {
    this.prototype = new Animal(name, 'Meow');
}

var fluffy = new Cat('Fluffy');

fluffy.speak();  // TypeError: undefined is not a function

为什么fluffy不能得到其原型的speak()方法?

如果您想学习如何在JS中继承, 请阅读本指南 prototype构造函数的属性,而不是实例

为什么fluffy不能得到其原型的speak()方法?

因为它不是原型。 你永远不会改变Cat.prototype 你设置Animal的方式,你必须在Cat内部调用Animal

function Cat(name) {
    Animal.call(this, name, 'Meow');
}

但是如果你想正确的原型继承,定义speakAnimal.prototype ,并通过建立继承Object.create

function Animal(name, sound) {
    this.name = name;
    this.sound = sound;
}

Animal.prototype.speak = function() {
    log(this.sound + '! My name is ' + this.name);
};

function Cat(name) {
    Animal.call(this, name, 'Meow');
}
Cat.prototype = Object.create(Animal.prototype);

问题是您在Animal构造函数中将speak设置为特权方法。

但是,永远不会为Cat实例调用该构造函数。

此外,您不能使用prototype属性来修改内部[[prototipe]]并更改应继承属性的对象。 您可以使用非标准__proto__或ECMAScript6 Object.setProtetipeOf ,但最好不要这样做。

相反,更好地使用这种方法:

function SuperClass(args) {
    // Here add SuperClass privileged properties
}

// Here add public properties to SuperClass.prototype

function SubClass(otherArgs) {
    // Add SuperClass privileged properties to SubClass instances:
    SuperClass.call(this, args);

    // Here add SubClass privileged properties
}

// Make SubClass instances inherit from SuperClass.prototype:
SubClass.prototype = Object.create(SuperClass.prototype);

// Fix constructor property, overriden in the line above
SubClass.prototype.constructor = SubClass;

// Here add public properties to SubClass.prototype

 function log(message) { document.body.innerHTML += '<p>' + message + '</p>'; } function Animal(name, sound) { this.name = name; this.sound = sound; } Animal.prototype.speak = function() { log(this.sound + '! My name is ' + this.name); }; function Cat(name) { Animal.call(this, name, 'Meow'); } Cat.prototype = Object.create(Animal.prototype); Cat.prototype.constructor = Cat; var fluffy = new Cat('Fluffy'); fluffy.speak(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM