简体   繁体   中英

how to use prototype to avoid copying of functions in javascript?

I had written this code to simulate OOP inheritance and calling baseclass in javascript and it works:

function Animal(name,age)
  {
    this._name = name; 
    this.setName = function (name) { this._name = name }
    this.getName = function() { return this._name }
  }

  function Cat(name,age)
  {
    Animal.call(this,name,age); // call baseclass constructor
    this.getName = function() { return Cat.prototype.getName.call(this)+", a cat" }
  }
  Cat.prototype = new Animal(); // will create the baseclass structure

  /// *****  actual execution  *****
  var puss = new Cat("Puss",3);
  var cheshire = new Cat("Cheshire",10);
  // do some actions
  console.log ( puss.getName() );
  // change cat's name
  puss.setName("Puss in boots");
  alert ( "new name -->"+puss.getName() );

problem is that, for each instance of "new Cat()" the "getName" and "setName" functions are replicated. I have read a lot of articles on prototyping but none addressed the issue of calling the baseclass function.

You should assign the methods to the prototype of the function, for example,

function Animal(name, age) {
    this._name = name;
    this._age = age;
}
Animal.prototype.getName = function () { return this._name; }
Animal.prototype.setName = function (value) { this._name = value; }

function Cat(name, age) {
    Animal.call(this, name, age);
}
Cat.prototype = new Animal();
Cat.prototype.getName = function () { 
    return Animal.prototype.getName.call(this) + ", a cat"; 
}

From http://phrogz.net/js/classes/OOPinJS2.html

Javascript does not have any sort of 'super' property, which would point to its parent class. Instead, you use the call() method of a Function object, which allows you to run a function using a different object as context for it. If you needed to pass parameters to this function, they would go after the 'this'.

In your case it works the same for functions as "methods", so you can do:

Animal.prototype.setName.call(this, name);

Are you looking for __proto__ which stores prototype data? https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/Proto

If you do a console.log(puss.__proto__.getName) you'll get what seems to be the "baseclass" function but I'm not sure how cross-browser is this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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