zoukankan      html  css  js  c++  java
  • Javascript的动态增加‘类’的方法

    1.我们可以为每一个实例对象增加方法。也就是说我们在每次使用‘类’之外的方法时候,都需要创建一次。

       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.如果想每一个通过Dog类创建的对象不要经过繁琐的引入就都可使用方法eat(),该如何呢?

       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;

    ,,,,,,,至此以后每个对象都可以使用Dog_eat()方法。

  • 相关阅读:
    Leetcode Unique Binary Search Trees
    Leetcode Decode Ways
    Leetcode Range Sum Query 2D
    Leetcode Range Sum Query
    Leetcode Swap Nodes in Pairs
    Leetcode Rotate Image
    Leetcode Game of Life
    Leetcode Set Matrix Zeroes
    Leetcode Linked List Cycle II
    CF1321A
  • 原文地址:https://www.cnblogs.com/imysql/p/5367658.html
Copyright © 2011-2022 走看看