「JavaScript」callメソッドでオブジェクトのコンストラクターを呼び出すサンプル

2021年2月9日

説明
call() メソッドは、 this の値と、独立して提供された引数によって関数を呼び出します。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//Personオブジェクト
function Person(name, age) {
this.name = name;
this.age = age;
}
//Userオブジェクト
function User(name, age) {
//callメソッド
Person.call(this, name, age);
this.category = 'systemerr';
}
// Engineerオブジェクト
function Engineer(name, age) {
//callメソッド
Person.call(this, name, age);
this.category = 'Engineer';
}
const cftA = new User('user001', 15);
const cftB = new Engineer('user002', 20);
console.log(cftA.name)
console.log(cftA.age)
console.log(cftA.category)
console.log("*******************")
console.log(cftB.name)
console.log(cftB.age)
console.log(cftB.category)
//Personオブジェクト function Person(name, age) { this.name = name; this.age = age; } //Userオブジェクト function User(name, age) { //callメソッド Person.call(this, name, age); this.category = 'systemerr'; } // Engineerオブジェクト function Engineer(name, age) { //callメソッド Person.call(this, name, age); this.category = 'Engineer'; } const cftA = new User('user001', 15); const cftB = new Engineer('user002', 20); console.log(cftA.name) console.log(cftA.age) console.log(cftA.category) console.log("*******************") console.log(cftB.name) console.log(cftB.age) console.log(cftB.category)
//Personオブジェクト
function Person(name, age) {
  this.name = name;
  this.age = age;
}
//Userオブジェクト
function User(name, age) {
  //callメソッド
  Person.call(this, name, age);
  this.category = 'systemerr';
}
// Engineerオブジェクト
function Engineer(name, age) {
    //callメソッド
  Person.call(this, name, age);
  this.category = 'Engineer';
}

const cftA = new User('user001', 15);
const cftB = new Engineer('user002', 20);


console.log(cftA.name)
console.log(cftA.age)
console.log(cftA.category)
console.log("*******************")
console.log(cftB.name)
console.log(cftB.age)
console.log(cftB.category)

実行結果
> “user001"
> 15
> “systemerr"
> “*******************"
> “user002"
> 20
> “Engineer"

JavaScript

Posted by arkgame