JSFiddle - React, Tailwind, and code Playground
by jseja
HTML
<!-- disregard this pane, html is shown in the "result" pane -->
<h4><strong>← Code Example from <a href="http://www.javascriptenlightenment.com/" target="_blank">JavaScript Enlightenment Book</a> by <a href="http://www.codylindley.com" target="_blank">Cody Lindley</a></strong></h4>
<p>JavaScript code is executed on page load. Click the "Run" button in the top bar to re-run the JavaScript code. Output is logged to the browsers console.</p>
JavaScript
var Person = function(x){
if(x) { this.fullName = x; };
};
Person.prototype.whatIsMyFullName = function() {
return this.fullName; // thisはPerson()ではなく、Person()から生成されたインスタンスを参照する
}
var cody = new Person('cody lindley');
var lisa = new Person('lisa lindley');
// プロトタイプ継承されたwhatIsMyFullName()メソッドを呼ぶ
console.log(cody.whatIsMyFullName(),lisa.whatIsMyFullName());
/* 次の例では、デフォルトのfullNameの値を設定する。プロトタイプチェーンが有効なので、インスタンスがfullNameプロパティを持っていない場合はプロトタイプチェーンをたどる。Object.prototypeにfullNameプロパティを設定し、PersonとObject両方のprototypeにfullNameプロパティを持つ。Notesを参照 */
Object.prototype.fullName = 'John Doe';
var john = new Person(); // 引数が渡されていないのでfullNameプロパティは設定されない
console.log(john.whatIsMyFullName()); // プロトタイプチェーンをたどって、'John Doe'を出力