Skip to content

Instantly share code, notes, and snippets.

@yuktse
Created February 25, 2014 09:15
Show Gist options
  • Save yuktse/9205519 to your computer and use it in GitHub Desktop.
Save yuktse/9205519 to your computer and use it in GitHub Desktop.
js 实现 OOP 的继承

js中实现OOP的继承,方法有很多,记录其中一种以备忘。

  // 定义基类构造函数
  var Product = function(type,price){
    this.type = type
    this.price = price // 函数中的this指代调用本函数的对象
  }
  
  // 在类的prototype中定义的属性,其生成的对象将会共用这些属性,指向同一个内存地址
  // 所以类的方法适合在prototype中定义。
  // 而成员变量适合在构造函数中定义,这样的属性是拥有独立的内存空间。
  Product.prototype.desc = function(){alert('this product type is '+ this.type + ' and price is ' + this.price)}
  
  // 定义扩展类
  var Car = function(wheels,price){
    Product.call(this,'car',price) // this(Car的实例)调用Product(‘car’, price)。于是Car的实例也有了属性type和price
    this.wheels = wheels // 属性wheels 是Car 类特有
  }
  Car.prototype = new Product(); // 这里目的是使Car类继承Product的所有方法
  var c = new Car(4,400);
  c.desc();
  // 覆盖基类的desc()
  Car.prototype.desc = function(){alert('i have '+this.wheels+' wheels')}
  c.desc();

今天为了了解prototype, call(), this 的用法,看资料看到头晕了~ 其实学习JS最好的方法是完全抛弃类、继承这些观念。深入去体会js function的原理与乐趣~ 关于prototype。如果访问某对象(object a)的属性,如果属性不存在,js就会到生成object a的类的prototype(object b)中去找。如果找不到,并且生成object b的类也有prototype,就会如此这般一直找下去。这个就称为原型链。

在原型链中只要一找到属性就会马上返回。如果到最后都没有找到就返回undefined

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment