node.js - Behavioral delegation introduced in the previous book about JavaScript you don't know
淡淡烟草味
淡淡烟草味 2017-07-03 11:42:23
0
3
881

https://github.com/getify/You...

This book believes that the object-related style is better than the object-oriented (prototype) style. The book also states that it does not support the class syntax of ES6, but it seems that the object-oriented style is usually used more often. How to choose?

Object-oriented style:

function Foo(who) {
    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();

Object association style:

var Foo = {
    init: function(who) {
        this.me = who;
    },
    identify: function() {
        return "I am " + this.me;
    }
};

var Bar = Object.create( Foo );

Bar.speak = function() {
    alert( "Hello, " + this.identify() + "." );
};

var b1 = Object.create( Bar );
b1.init( "b1" );
var b2 = Object.create( Bar );
b2.init( "b2" );

b1.speak();
b2.speak();
淡淡烟草味
淡淡烟草味

reply all(3)
扔个三星炸死你

What do you think of the programming style advocated in "JS You Don't Know"?

I think Teacher He’s answer is quite good.

曾经蜡笔没有小新

Personally, I think if you have obsessive-compulsive disorder, choose delegation, and if you don’t have obsessive-compulsive disorder, choose object-oriented. The author seems to be an obsessive-compulsive disorder who can't see a grain of sand in his eyes, and is particularly resistant to individual problems brought about by classes. Which method you choose is entirely a personal preference. No matter which method you choose, understanding its essence or based on the prototype chain is the key. I used to work in Java and have mild obsessive-compulsive disorder, so I am more accepting of classes ^_^

伊谢尔伦

How to write code is of course a very personal matter, related to your habits and preferences. But I think there are some basic principles for reference:

  1. Improve development efficiency

  2. Reduce error rate
    3. Easy to read and understand

A way that meets these three points is a good way. Violating these three points and insisting on a certain way is not worth advocating.

When you choose how to write code, why not try them all and compare them according to these three principles? You don’t have to do it just because of what someone says.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template