JS OOPS更好的理解

时间:2019-04-12 11:09:31

标签: javascript

我只是在Js中讲招。我知道简单的js继承。以下代码只是clientUser扩展了用户,他可以访问User函数。因为我只是从用户完全object.create()复制引用obj。从现在开始,我只能理解以下简单代码

function User(a,n){
this.name=n;
this.age=a;
}

User.prototype.getters= function(){
 document.write (`name is ${this.name} and age is ${this.age}****`)
}

john = new User('john-smith', 18);
john.getters();

function ClientUser(a,n,i){
 User.call(this,a,n);
}

ClientUser.prototype = Object.create(User.prototype)
c = new ClientUser('groot',23,'smalID');
c.getters();

CoffeeScript生成的代码

<!-- language: cofeee -->

class Bear
  constructor: (@name) ->

  attack: ->
    "#{@name} the bear attacks with his bare paws!"

//oswalt = new Bear "Oswalt"
rodrigo = new BearWithChainsawHands "Rodrigo"
//console.log rodrigo.attack()
console.log oswalt.attack()

我只是试图了解这段代码的背后过程。我知道在CoffeeScript中,它的工作方式就像super()。但我听不懂js中的代码。

var Bear, BearWithChainsawHands, rodrigo;
var __hasProp = Object.prototype.hasOwnProperty;
var __extends = function(child, parent) {
  for (var key in parent) {
    if (__hasProp.call(parent, key)) {
     debugger;
     console.log(key)
      child[key] = parent[key];
    }
    else{
      debugger
    }
  }
  function ctor() { this.constructor = child; }

  ctor.prototype = parent.prototype;
  child.prototype = new ctor;
  child.__super__ = parent.prototype;

  return child;
};

function Bear(name) {
  this.name = name;
}

Bear.prototype.attack = function() {
  return "" + this.name + " the bear attacks with his bare paws!";
};

function BearWithChainsawHands() {
  BearWithChainsawHands.__super__.constructor.apply(this, arguments);
}

__extends(BearWithChainsawHands, Bear);

BearWithChainsawHands.prototype.attack = function() {
  return BearWithChainsawHands.__super__.attack.apply(this, arguments) + " BY THE WAY, HIS PAWS ARE CHAINSAWS.";
};

rodrigo = new BearWithChainsawHands("Rodrigo");
console.log(rodrigo.attack());
document.write(rodrigo.attack())

任何人都可以解释__extend()的工作用法吗?和代码流?

0 个答案:

没有答案