Home > Web Front-end > JS Tutorial > body text

Implementation method of dynamically adding classes in Javascript

高洛峰
Release: 2016-12-09 15:34:21
Original
1049 people have browsed it

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();所以也只能该对象使用
Copy after login

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;
Copy after login

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


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!