简体   繁体   English

简单的JavaScript原型示例

[英]Simple javascript prototype example

I am trying to give a simple example of prototype inheritance in javascript but its not running. 我试图在javascript中给出原型继承的简单示例,但是它没有运行。 Kindly help! 请帮助!

HTML 的HTML

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

Yes, you can add properties to a prototype... as long as the prototype actually exists . 是的,您可以向原型添加属性...,只要该原型实际存在即可 In your case, you have to initialize first the prototype. 对于您的情况,您必须首先初始化原型。 For example: 例如:

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

But a nicer way to define a prototype is: 但是定义原型的更好方法是:

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);

Easier way for you. 为您提供更简便的方法。 You can use the non constructor way to create objects with existing objects thus using prototypical inheritance in javascript. 您可以使用非构造函数的方式创建具有现有对象的对象,从而在javascript中使用原型继承。 The other is using functions. 另一种是使用功能。

Your animal question has been asked before: Basic JavaScript Prototype and Inheritance Example for Animals , pls follow other javascript protoytype posts here in stackoverflow as there as numerous and enough time has been spent on them. 之前已经问过您的动物问题:动物的基本JavaScript原型和继承示例 ,请在stackoverflow中关注此处的其他JavaScript原型类型帖子,因为已经在它们上面花费了许多时间。 Utilize and be a pro. 利用并成为专业人士。

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

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

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