About js object Association Styles

speechless. At first, I thought that all the great gods knew this style without adding code. as a result, the problem was trampled on, and the hostility in your community was really heavy. I admire and admire it.

learned about this code style while watching js you don"t know, but it seems (? ) this code style is not particularly common, is it because there are any drawbacks in this style

the following is the object association style & the comparison of object-oriented styles

// "" 
function Foo() {
   this.me = who;
}
Foo.prototype.identify = function() {
     return "I am "+ this.me;
}
function Bar(who) {
    Foo.call(this, who);
}
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.speak = function() {
    alert("hello, "+ this.identify() + ".");
};
var b1 = new Bar("b1");
var b2 = new Bar("b2");

b1.speak();
b2.speak();
//BarFoo,b1b2b1Bar.prototypeFoo.prototype
//
Foo = {
     init: function(who) {
          this.me = who;
      },
      identify: function() {
            return "i am "+ this.me
      }
};
Bar = Object.create(Foo);
Bar.speak = function() {
     alert("hello, "+ this.identify() + ".");
}
var b1 = Object.create(Bar);
b1.init("b1")l
var b2 = Object.create(Bar);
b2.init("b2");
b1.speak();
b2.speak();
//[[prototype]]b1BarBarFoo,new
Mar.05,2021

it's your fault not to describe the problem clearly.

the original driving force for inheritance is reuse code.
in this respect, as you said, object associations are definitely better if you just reuse methods.

then why are object associations used less?
1. There is no normal object recognition relationship
it is generally believed that the prototype points to the parent class, and the object association does not conform to this relationship.
2. The usual requirement is not only to inherit methods, but also to initialize and inherit properties.
like classic inheritance in your code, Bar inherits the properties of Foo and can also be initialized.
object associations are not initialized, and although properties can be bound, their properties are common to the instance as prototypes.

function Bar(who) {
  Foo.call(this, who);
}

3. Classical inheritance does seem to be higher than object association, and no one wants to be inferior.
4. When we do inheritance, we simply don't expect to use objects directly, but habitually use constructors for inheritance.

Menu