// 测试 const p1 = new Person1('张三'); console.log(p1.introducSelf()); // 大家好,我是张三

const p2 = new Person2('李四'); console.log(p2.introducSelf()); // 大家好,我是李四 Person2.mySelf(); // 非原型链上的函数

/**

  • Person1 构造函数
  • @param {string} name */ function Person1(name) { // 属性 this.name = name; // 行为 this.introducSelf = function() { return 大家好,我是${name}; } }

/**

  • Person2 构造函数: 定义函数
  • @param {string} name */ function Person2(name) { // 属性 this.name = name; }

// 在原型链上定义要继承的函数 Person2.prototype.introducSelf = function() { return 大家好,我是${this.name}; }

// 非原型链方法,属于 Person2 对象自身的函数 Person2.mySelf = function() { console.log('非原型链上的函数'); }

JavaScript 面向对象编程:构造函数、原型链与继承

原文地址: https://www.cveoy.top/t/topic/os9s 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录