English 中文(简体)
Java 遗产继承:称为超级建筑或使用原型链?
原标题:Javascript inheritance: call super-constructor or use prototype chain?
最佳回答

真正问题的答案是,你必须做到:

  • Setting the prototype to an instance of the parent initializes the prototype chain (inheritance), this is done only once (since the prototype object is shared).
  • Calling the parent s constructor initializes the object itself, this is done with every instantiation (you can pass different parameters each time you construct it).

因此,在确立遗产时,你不应把父母称为 construct。 只有在瞬间出现从他人继承的物体时。

克里斯·摩根的答案几乎完整,缺少少量细节(建筑财产)。 让我提出确定遗产的方法。

function extend(base, sub) {
  // Avoid instantiating the base class just to setup inheritance
  // Also, do a recursive merge of two prototypes, so we don t overwrite 
  // the existing prototype, but still maintain the inheritance chain
  // Thanks to @ccnokes
  var origProto = sub.prototype;
  sub.prototype = Object.create(base.prototype);
  for (var key in origProto)  {
     sub.prototype[key] = origProto[key];
  }
  // The constructor property was set wrong, let s fix it
  Object.defineProperty(sub.prototype,  constructor , { 
    enumerable: false, 
    value: sub 
  });
}

// Let s try this
function Animal(name) {
  this.name = name;
}

Animal.prototype = {
  sayMyName: function() {
    console.log(this.getWordsToSay() + " " + this.name);
  },
  getWordsToSay: function() {
    // Abstract
  }
}

function Dog(name) {
  // Call the parent s constructor
  Animal.call(this, name);
}

Dog.prototype = {
    getWordsToSay: function(){
      return "Ruff Ruff";
    }
}    

// Setup the prototype chain the right way
extend(Animal, Dog);

// Here is where the Dog (and Animal) constructors are called
var dog = new Dog("Lassie");
dog.sayMyName(); // Outputs Ruff Ruff Lassie
console.log(dog instanceof Animal); // true
console.log(dog.constructor); // Dog

See my blog post for Even further syntactic food when establishing levels. http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html

Technique copied from Ext-JS and 。 http://www.uselesspickles.com/class_library/。 https://stackoverflow.com/users/1397311/ccnokes”

问题回答

理想的办法是:not do prod_dept.prototype = New Products();,因为这称作Product。 因此,理想的办法是除建筑商外衣,如:

function Product(...) {
    ...
}
var tmp = function(){};
tmp.prototype = Product.prototype;

function Prod_dept(...) {
    Product.call(this, ...);
}
Prod_dept.prototype = new tmp();
Prod_dept.prototype.constructor = Prod_dept;

然后,超级建筑商被停在施工时间,这是你想要的,因为你也可以通过这些参数。

如果看像谷歌关闭图书馆这样的情况,就会看看看它们是如何做到的。

如果你在贾瓦文中做了面向目标的方案拟订工作,你将知道你可以设立以下类别:

Person = function(id, name, age){
    this.id = id;
    this.name = name;
    this.age = age;
    alert( A new person has been accepted );
}

So far our class person only has two properties and we are going to give it some methods. A clean way of doing this is to use its prototype object. Starting from JavaScript 1.1, the prototype object was introduced in JavaScript. This is a built in object that simplifies the process of adding custom properties and methods to all instances of an object. Let s add 2 methods to our class using its prototype object as follows:

Person.prototype = {
    /** wake person up */
    wake_up: function() {
        alert( I am awake );
    },

    /** retrieve person s age */
    get_age: function() {
        return this.age;
    }
}

Now we have defined our class Person. What if we wanted to define another class called Manager which inherits some properties from Person. There is no point redefining all this properties again when we define our Manager class, we can just set it to inherit from the class Person. JavaScript doesn t have built in inheritance but we can use a technique to implement inheritance as follows:

我们设立了继承人阶层(名称是任意的)

Now let s give our inheritance class a method called extend which takes the baseClass and subClassas arguments. Within the extend method, we will create an inner class called inheritance function inheritance() { }. The reason why we are using this inner class is to avoid confusion between the baseClass and subClass prototypes. Next we make the prototype of our inheritance class point to the baseClass prototype as with the following code: inheritance.prototype = baseClass. prototype; Then we copy the inheritance prototype into the subClass prototype as follows: subClass.prototype = new inheritance(); The next thing is to specify the constructor for our subClass as follows: subClass.prototype.constructor = subClass; Once finished with our subClass prototyping, we can specify the next two lines of code to set some base class pointers.

subClass.baseConstructor = baseClass;
subClass.superClass = baseClass.prototype;

这里是我们扩展职能的全面法典:

Inheritance_Manager.extend = function(subClass, baseClass) {
    function inheritance() { }
    inheritance.prototype = baseClass.prototype;
    subClass.prototype = new inheritance();
    subClass.prototype.constructor = subClass;
    subClass.baseConstructor = baseClass;
    subClass.superClass = baseClass.prototype;
}

Now that we have implemented our inheritance, we can start using it to extend our classes. In this case we are going to extend our Person class into a Manager class as follows:

我们界定管理阶层

Manager = function(id, name, age, salary) {
    Person.baseConstructor.call(this, id, name, age);
    this.salary = salary;
    alert( A manager has been registered. );
}

继承人

Inheritance_Manager.extend(Manager, Person);

If you noticed, we have just called the extend method of our Inheritance_Manager class and passed the subClass Manager in our case and then the baseClass Person. Note that the order is very important here. If you swap them, the inheritance will not work as you intended if at all. Also note that you will need to specify this inheritance before you can actually define our subClass. Now let us define our subClass:

我们可以增加以下方法。 我们的管理人员班子将永远拥有个人班子界定的方法和财产,因为它继承了该班。

Manager.prototype.lead = function(){
   alert( I am a good leader );
}

Now to test it let us create two objects, one from the class Person and one from the inherited class Manager:

var p = new Person(1,  Joe Tester , 26);
var pm = new Manager(1,  Joe Tester , 26,  20.000 );

Feel free to get full code and more comments at: http://www.cyberminds.co.uk/blog/articles/how-to-implement-javascript-inheritance.aspx





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签