Home  >  Article  >  Web Front-end  >  Implementation method of dynamically adding classes in Javascript

Implementation method of dynamically adding classes in Javascript

高洛峰
高洛峰Original
2016-12-09 15:34:211139browse

1. We can add methods to each instance object. In other words, we need to create it every time we use a method outside the 'class'.

  function Dog(){
 
  window.alert('I am a dog!');
 
 }
 
 var dog1=new Dog();//实例化一个对象
 
//现在由于类Dog功能单一,无法满足对象dog1的需要,现在就要考虑为对象dog1新增加一个方法
 
 function eat(){
 
  window.alert('I like eat bone!');
 
}
 
dog1.Dog_eat=eat;
 
dog1.Dog_eat();//此时就可以调用方法eat了,不过使用的是一个指针Dog_eat指向eat();所以也只能该对象使用

2. What if you want every object created through the Dog class to use the method eat() without having to go through tedious introduction?

function Dog(){
 
  window.alert('I am a dog!');
 
 }
 
 Dog.prototype.Dog_eat=function(){
 
  window.alert('I like eat bone')
 
}
 
var dog1=new Dog();
 
dog1.Dog_eat;
 
var dog2=new Dog();
 
dog2.Dog_eat;

From now on, every object can use the Dog_eat() method.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn