javascript Class-based vs. prototype-based

Class-based object-oriented languages, such as Java and C++:
1.class定义了所有的属性
2.instance来实现class

A prototype-based language, such as JavaScript
1.只有object,任何object可以指定自己的属性,无论是在创建还是运行时
1.任何object可以以prototype形式和其他的object关联,来共享属性

function Employee() {
    this.name = '';
    this.dept = 'general';
}
public class Employee {
   public String name = "";
   public String dept = "general";
}

继承

function Manager() {
  Employee.call(this);
  this.reports = [];
}
Manager.prototype = Object.create(Employee.prototype);
Manager.prototype.constructor = Manager;

function WorkerBee() {
  Employee.call(this);
  this.projects = [];
}
WorkerBee.prototype = Object.create(Employee.prototype);
WorkerBee.prototype.constructor = WorkerBee;
public class Manager extends Employee {
   public Employee[] reports = 
       new Employee[0];
}



public class WorkerBee extends Employee {
   public String[] projects = new String[0];
}

参考:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model

发布了1794 篇原创文章 · 获赞 582 · 访问量 154万+

猜你喜欢

转载自blog.csdn.net/claroja/article/details/104313440