两个对象之间的Javascript原型

时间:2016-04-19 12:07:52

标签: javascript javascript-objects

如果我有医生对象,患者对象和检查(对象内部有少量不同的检查功能)。我该怎么写 医生(约翰)正在检查那种患者的检查类型?如果我不清楚我的问题,请在高级对不起...

我试过这个。

Exam.prototype.John = function(Doctor){
    return this.bloodPresure();
}

1 个答案:

答案 0 :(得分:0)

  • 从可靠来源查找模式:MDN - Prototype - Examples
  • 然后将相关内容应用于代码。
  • 只是逐步完成这个例子,我学会了一些东西。

SNIPPET



// Define Doctor constructor
var Doctor = function() {
  this.proscribe = true;
};

// Add intruct method to Doctor.prototype
Doctor.prototype.instruct = function() {
  if (this.proscribe) {
    console.log('Proscription filled by ' + this.name + ' Do not operate heavy machinery');
  }
};

// Define the generalPractioner constructor
var generalPractitioner = function(name, title) {
  Doctor.call(this);
  this.name = name;
  this.title = title;
};

// Create a generalPractitioner.prototype object that inherits from Doctor.prototype.
generalPractitioner.prototype = Object.create(Doctor.prototype);
generalPractitioner.prototype.constructor = generalPractitioner;

// Instantiate instruct method
generalPractitioner.prototype.instruct = function() {
  if (this.proscribe) {
    console.log('Proscribed by ' + this.title + this.name + '  Do not operate heavy machinery');
  }
};

// Define the Pharmacist constructor
var Pharmacist = function(name) {
  Doctor.call(this);
  this.name = name;
};

// Create a Pharmacist.prototype object that inherits from Doctor.prototype.
Pharmacist.prototype = Object.create(Doctor.prototype);
Pharmacist.prototype.constructor = Pharmacist;

// Define the Intern constructor
var Intern = function(name) {
  Doctor.call(this);
  this.name = name;
  this.proscribe = false;
};

// Create a Intern.prototype object that inherits from Doctor.prototype.
Intern.prototype = Object.create(Doctor.prototype);
Intern.prototype.constructor = Intern;

// Usage
var john = new generalPractitioner('John', 'Dr.');
var mike = new Pharmacist('Mike');
var ann = new generalPractitioner('Ann', 'Dr.');
var vick = new Pharmacist('Vick');
var intern = new Intern('Intern');

john.instruct();
// Proscribed by Dr. John Do not operate heavy machinery'

mike.instruct();
// Proscription filled by Mike Do not operate heavy machinery'

ann.instruct();
// Proscribed by Dr. Ann Do not operate heavy machinery'

vick.instruct();
// Proscription filled by Vick Do not operate heavy machinery'

intern.instruct();

<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
&#13;
&#13;
&#13;