ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 认识面向对象   1. 一切事物皆对象   2. 对象具有封装和继承性   3. 信息隐藏 ## 基本面向对象 ~~~ <script> // 定义一个基本的对象 var parson = { name:"rose", age:25, eat:function(){ // 对象eat方法 alert('eat'); } }; console.log(parson); </script> ~~~ ## 函数构造器构造对象 ~~~ <script> function person(){ } person.prototype = { name : "rose", age : 25, eat : function (){ console.log("from function obj"); return true; } }; var oPerson = new person(); // 创建对象 console.log(oPerson.age); // 调用对象属性 console.log(oPerson.name); console.log(oPerson.eat()); // 调用对象方法 </script> ~~~ ## 深入JavaScript面向对象 ~~~ <script type="text/javascript"> function people(){ } people.prototype.say = function (){ console.log("hello!"); } function student(){ } student.prototype = new people(); // 通过new对象的方式 使得student类继承自people var s = new student(); s.say(); // hello! 继承自父类方法成功 student.prototype.say = function (){ console.log('stu say hello!'); } var s = new student(); s.say(); // stu say hello! 父类方法被复写了 </script> ~~~ 那如何在子类中调用父类呢? ~~~ <script type="text/javascript"> function people(){ } people.prototype.say = function (){ console.log("hello!"); } function student(){ } student.prototype = new people(); // 通过new对象的方式 使得student类继承自people var s = new student(); s.say(); // hello! 继承自父类方法成功 var superSay = student.prototype.say; // 将父类的方法赋值给变量 student.prototype.say = function (){ superSay.call(this); // 调用call方法 console.log('stu say hello!'); } var s = new student(); s.say(); // stu say hello! 父类方法被复写了 </script> ~~~ ## 另外 闭包 ~~~ <script type="text/javascript"> (function(){ function people(name){ // 传递参数 this.name = name; } people.prototype.say = function (){ console.log("hello!"+ this.name); } window.people = people; }()); (function(){ function student(name){ // 传递参数 this.name = name; } student.prototype = new people(); // 通过new对象的方式 使得student类继承自people var superSay = student.prototype.say; // 将父类的方法赋值给变量 student.prototype.say = function (){ superSay.call(this); // 调用方法 console.log('stu say hello!'+this.name); } window.student = student; }()); var s = new student('rose'); s.say(); // stu say hello! 父类方法被复写了 // 最后结果打印了 hello!rose | stu say hello!rose </script> ~~~