var person1 = new Person('Alice');
person1.sayHello(); // 输出:Hello, Alice登录后复制
继承属性和方法:
function Student(name, grade) {
Person.call(this, name); // 调用父类构造函数
this.grade = grade;
Student.prototype = Object.create(Person.prototype); // 继承父类原型
Student.prototype.constructor = Student; // 修复构造函数
Student.prototype.study = function() {
console.log(this.name + ' is studying in grade ' + this.grade);
var student1 = new Student('Bob', 5);
student1.sayHello(); // 输出:Hello, Bob
student1.study(); // 输出:Bob is studying in grade 5登录后复制查找属性和方法:
console.log(student1.name); // 输出:Bob
console.log(student1.__proto__ === Student.prototype); // 输出:true
console.log(student1.__proto__.__proto__ === Person.prototype); // 输出:true
console.log(student1.__proto__.__proto__.__proto__ === Object.prototype); // 输出:true
console.log(student1.hasOwnProperty('name')); // 输出:true
console.log(student1.hasOwnProperty('sayHello')); // 输出:false登录后复制

发表评论 取消回复