I don't understand Crockford on [removed] The Way Forward

后端 未结 4 1058
北恋
北恋 2021-01-30 05:45

In a lecture called "The Way Forward", Douglass Crockford shares that he no longer uses "new" in his JavaScript, and is weaning himself off of "this&quo

4条回答
  •  礼貌的吻别
    2021-01-30 06:30

    Obviously some other good answers here, but TL;DR:

    Why does this snippet make the following assignment?

    that.method = method

    He's "extending" the that object, adding a locally defined method (unfortunately named) method. It's no more complex than that.

    function animal_constructor(init){
        return {};
    }
    
    function dog_constructor(init) {
        // Create a generic animal object
        var dog = animal_constructor(init),
            // Define a local function variable called 'bark'
            bark = function() {
                alert('woof!');
            };
    
        // Add the 'bark' function as a property of the generic animal
        dog.bark = bark;
        // Return our now-fancy quadriped
        return dog;
    }
    
    // Try it out
    var init = {},
        animal = animal_constructor(init),  // generic animals can't bark
        yeller = dog_constructor(init);     // fancy dog-animals can!
    
    yeller.bark();  // > woof!
    animal.bark();  // > Uncaught TypeError: undefined is not a function 

提交回复
热议问题