简单 javascript 原型示例

Simple javascript prototype example

我试图在 javascript 中给出原型继承的简单示例,但它不是 运行。请帮忙!

HTML

<script> 
var animal = {eats: 'true'};
animal.prototype.name = "Lion";
console.log(animal);
</script> 

对您来说更简单的方法。您可以使用非构造函数方式使用现有对象创建对象,从而使用 javascript 中的原型继承。另一个是使用函数。

之前有人问过你的动物问题:,请关注 Whosebug 中的其他 javascript 原型帖子,因为在这些帖子上花费了足够多的时间。利用并成为专业人士。

var animal = { name: 'Lion'};
var myanimal = Object.create(animal)
myanimal.eats = "true";
console.log(myanimal.name);

是的,您可以向原型添加属性...只要原型实际 存在 。在您的情况下,您必须首先初始化原型。例如:

var animal = {eats: 'true'};
animal.prototype={};
animal.prototype.name = "Lion";
console.log(animal);

但是定义原型的更好方法是:

var Animal=function(name){
    this.name=name;
}

// Add new members to the prototype:
Animal.prototype.toString=function()
{
    return "animal "+this.name;
}

// Instance objects:
var a1=new Animal("panther");
console.log(a1.toString());
var Animal = function() {
  this.eats = 'true';
};

Animal.prototype.name = 'Lion';

var a = new Animal;

console.log(a.name);