简体   繁体   中英

Using `this` vs Object.create(prototype)

I've been using JSLint to help me relearn how to code properly. The program doesn't like using this in my code, so I've settled on using self=Object.create(MyType.prototype) . Are there any pitfalls or limitations for using this pattern? Am I just being too verbose by avoiding this ? Here is an example of how I've been writing constructor functions with prototype inheritance:

function MyType(args) {
    var privateVar1 = "value",
        self = Object.create(MyType.prototype);

    function privateFunction() { )

    self.publicMethod1 = function(aa) {
        // do stuff with private vars & self. Ex:
        var methodVar = privateVar1 + aa;
        self.publicProperty = args;
        privateFunction();
        return methodVar;
    };

    return self;
}
MyType.prototype = {
    publicProperty: "initial value",
    publicMethod2: function (aa) { }
}

function MyType2(args) {
    var self = Object.create(MyType2.prototype);
    return self;
}
MyType2.prototype = Object.create(MyType.prototype);
MyType2.prototype.publicMethod3 = function (aa) { };

I've teaching myself JavaScript again after a long layoff. It has been about ten years since I've done anything. The Internet never really forgets, but progress still happens. So some tutorials seem to be based on older standards/suggestions while newer articles contradict them. It is becoming confusing to sort out which articles are current and which are out-of-date. I could use some help please.

The JSLint tool only tells you how Douglas Crockford wants you to use JavaScript. The name JSLint is rather misleading, as it doesn't verify code according to the language standards, it verifies code according to Douglas Crockfords views on how to use the language. If you want to follow his advice to the letter, then you are doing it right.

Other tutorials aren't necessarily out of date or wrong, they are mostly just different. There are many different ways of using JavaScript, not only one.

Personally, I would write:

function MyType(args) {
  var privateVar1 = "value";

  function privateFunction() { )

  this.publicMethod1 = function(aa) {
    // do stuff with private vars & this. Ex:
    var methodVar = privateVar1 + aa;
    this.publicProperty = args;
    privateFunction();
    return methodVar;
  };
}

MyType.prototype = {
  publicProperty: "initial value",
  publicMethod2: function (aa) { }
}

function MyType2(args) {
}
MyType2.prototype = Object.create(MyType.prototype);
MyType2.prototype.publicMethod3 = function (aa) { };

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