JavaScript -- 面向对象的简单分析
2016-05-04 16:33
561 查看
// 第一种:直接赋值: //var person = { // name:"iwen", // age:"30", // eat:function(){ // alert("能吃") // } //} //alert(person.name); // 使用原型为对象赋值 function Person(){ } Person.prototype = { name:"iwen", age:"30", eat:function(){ alert("我在吃") } } var p = new Person(); alert(p.eat); //------------第二类--------------// // 对象之间的调用 /* function People(name){ this._name = name; } People.prototype.say = function(){ alert("hello,"+this._name); } function Student(name){ this.name = name; } Student.prototype = new People("iwen"); var superSay = Student.prototype.say; Student.prototype.say = function(){ superSay.call(this); alert("stu-hello"); } var s = new Student("iwen"); s.say() */ //------ 上述可以改写为:(将对象属性封装为私有属性) (function(){ var n = "ime" function People(name){ this._name = name; } People.prototype.say = function(){ alert("peo-hello,"+this._name+n); } window.People = People; // 如果想让外界使用,就让他赋给window }()); (function(){ function Student(name){ this._name = name; } Student.prototype = new People(); var superSay = Student.prototype.say; Student.prototype.say = function(){ superSay.call(this); alert("stu-hello,"+this._name); } window.Student = Student; }()); var s = new Student("iwen"); s.say() // ------------第三类--------------- // /* // 无参数的赋值 // 全部通过对象赋值的操作 function Person(){ var _this = {} _this.sayHello = function(){ alert("hello"); } return _this; } function Teacher(){ var _this = Person(); var superSay = _this.sayHello(); _this.sayHello = function(){ alert("Thello"); } return _this; } var t = Teacher(); t.sayHello(); */ //-------以上是无参数,下面是有参数类型的------// // 写完后,可以尝试将第一个函数块封装起来,对比一下使用区别 (function(){ var n = "Tom"; function Person(name){ var _this = {} _this._name = name; _this.sayHello = function(){ alert("hello,"+this._name+ n); } return _this; } window.Person = Person; }()) function Teacher(name){ var _this = Person(name); var superSay = _this.sayHello(); _this.sayHello = function(){ alert("Thello"+this._name); } return _this; } var t = Teacher("iwen"); t.sayHello();
可以发现,对于初学者,最后一种是最容易理解与学习的,需要注意的是,在有参的时候,需要现将参数提取出来,再进行使用;
相关文章推荐
- 学JavaScript七大注意事项【必看】
- jsp ,servlet中session ,Cookie 相关知识
- 优雅的图片翻转实现方式rollover.js
- jsonp方式解决跨域共享问题
- JavaScript 异步编程
- HTML中 js执行环境切换
- 关于js原型继承
- javascript 匿名函数的理解(透彻版)
- FastJSON 简介及其Map/JSON/String 互转
- js利用数组创建图片对象
- 对象的创建:工厂模式/构造函数模式/原型模式 (笔记)
- JS只能输入数字,数字和字母等的正则表达式
- JS转换HTML转义符
- .net面试题(.Net+Html+Javascript)
- js
- nwjs学习笔记--01
- Javascript 严格模式详解
- JavaScript 复选框全选和反选
- 常用正则表达式大全,手机、电话、邮箱、身份证(最严格的验证)、IP地址、网址、日期等,一般前台js验证,来这里就够了...
- ionic js学习笔记