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
登录后复制

点赞(831) 打赏

评论列表 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部