Javascript面向对象
认识面向对象
- 面向对象中的概念
- 1).一切事物皆对象
- 2).对象具有封装和继承特性
- 3).信息隐藏
构造对象:
代码示例(最简单的,字面式的对象声明):
//基本面向对象 var person = { name:"Lillian", age:20, eat:function(){ alert("吃货"); } } alert(person.name);
代码示例(另一种方式构造对象):
//函数构造器构造对象 function Person(){ } //指定Person的属性 Person.prototype = { name:"Lillian", age:20, eat:function(){ alert("吃货"); } } var p = new Person();
这里要注意,虽然var p = new Person();
和在Java中构造一个对象的句子是一样的,但实际上他们是不同的!
JS面向对象(1)
Javascript中并不存在类的概念,但是我们可以用function
来模拟类。
代码示例:
//将People这个函数当作类来使用 function People(){ } //书写类中的属性和方法 People.prototype.say = function(){ alert("hello") } //继承类 function Student(){ } //只要实现Student扩展自People即可 Student.prototype = new People(); //测试是否“继承”成功 var s = new Student(); s.say();
运行之后,发现s
可以调用say()
方法。弹出:
如果Student()
中也有say()
方法,那么最后调用的还是Student
中的say()
方法,此时在子类中,父类的方法被重写。
代码示例:
function People(){
}
People.prototype.say = function(){
alert("hello");
}
function Student(){
}
Student.prototype = new People();
Student.prototype.say = function(){
alert("stu-hello");
}
var s = new Student();
s.say();
运行之后将会弹出:
如果在“子类”重写了方法,但还是想调用“父类”中的方法
代码示例:
function People(){ } People.prototype.say = function(){ alert("hello"); } function Student(){ } Student.prototype = new People(); var superSsay = Student.prototype.say; Student.prototype.say = function(){ superSsay.call(this); alert("stu-hello"); } var s = new Student(); s.say();
添加如上的两行代码,最终运行将会调用People
和Student
中的say
方法。
在“父类”中添加参数name
代码示例:
function People(name){ this._name = name; } People.prototype.say = function(){ alert("peo-hello"+this._name); } function Student(name){ this._name = name; } Student.prototype = new People(); var superSsay = Student.prototype.say; Student.prototype.say = function(){ superSsay.call(this); alert("stu-hello"+this._name); } var s = new Student("Lillian"); s.say();
执行之后,依次弹出:和
可以看到参数的传递。
将函数进行封装
代码示例:
(function(){ var n = "LaLa" function People(name){//将People这个函数当作类来使用 this._name = name; } //书写类中的属性和方法 People.prototype.say = function(){ alert("peo-hello"+this._name+n); } //外部接口 window.People = People; }());
在本包内,n
可以随意被引用,如果包的外部想引用,就需要window
公开一个接口。封装的格式如下:
JS面向对象(2)
通过对象赋值操作来进行“类”的继承等
代码示例:
//创建一个“类” function Person(){ //创建一个空对象,将其他的方法和属性通过这个空对象来承载 var _this = {}; _this.sayHello = function(){ alert("Hello yoyo!") } return _this; } //进行继承 function Teacher(){ //整个Person中的内容都传给了_this var _this = Person(); return _this; } var t = Teacher(); t.sayHello();
运行后,弹出:。同理,它也可以复写“父类”的方法。
相比起传统的继承方法,可以看看Javascript apply()和call()方法