版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/miao_9/article/details/73087829
要掌握好 JavaScript,首先一点是必须摒弃一些其他高级语言如 Java、C# 等类式面向对象思维的干扰,全面地从函数式语言的角度理解 JavaScript 原型式面向对象的特点。
JavaScript 语言是通过一种叫做 原型(prototype)的方式来实现面向对象编程的
认识面向对象
1、面向对象中的概念:
(1):一切事物皆对象
(2):对象具有封装和继承特性
(3):对象与对象之间使用消息通信,各自存在信息隐藏
最基本的面向对象
字面式声明(literal notation)
var person={
name:"miao",
age:20,
eat:function () {
alert("能吃")
}
}
alert(person.name);
函数构造器构造对象
每个构造器(constructor)实际上是一个 函数(function) 对象, 该函数对象含有一个“prototype”属性用于实现 基于原型的继承(prototype-based inheritance)和 共享属性(shared properties)。对象可以由“new 关键字 + 构造器调用”的方式来创建。
Java和JavaScript这两门语言的 new含义毫无关系,因为其对象构造的机理完全不同。JS 这里仅仅是借用了关键字 new,仅此而已;换句话说, 完全可以用其它 非new 表达式来用调用构造器创建对象。
function Peroson() {
}
Peroson.prototype={
name:"miao",
age:20,
eat:function () {
alert("能吃")
}
}
var p = new Peroson();
p.name
p.age
p.eat();
深入JavaScript面向对象
//信息封装
(function () {
var n = "ime";
function People(name) {
this._name = name;
}
People.prototype.say = function () {
alert("peo-hello"+this._name);
}
window.People = People;//提供一个外部接口
}());
(function () {
function Student(name) {
this._name = name;
}
Student.prototype = new People(); //Student继承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("miao");
s.say();
(function () {
var n = "ime";
function Person(name) {
var _this = { }
_this._name = name;
_this.sayHello = function () {
alert("p-hello"+_this._name+n);
}
return _this;
}
window.Person = Person;
}());
function Teacher(name) {
var _this = Person(name);
var superSay = _this.sayHello;
_this.sayHello = function () {
superSay.call(_this);
alert("t-hello" + _this._name);
}
return _this;
}
var t = Teacher("miao");
t.sayHello();