js面向对象

来源:互联网 发布:淘宝店铺被扣48分 编辑:程序博客网 时间:2024/06/08 19:36

面向对象编程在如今的js中越来越重要,现在花点时间总结一下面向对象

面向对象的两个基本概念(类,实例)
1. 类:类是对象的类型模板
2. 实例:实例是根据类创建的对象

但是js中没有类的概念,所以就用对象来充当所谓的’类’,这个对象的属性”(property)和”方法”(method)

原型链

每个对象都具有一个名为_ proto _的属性
每个构造函数(构造函数标准为大写开头,如Function(),Object()等等JS中自带的构造函数,以及自己创建的)都具有一个名为prototype的方法(注意:既然是方法,那么就是一个对象(JS中函数同样是对象),所以prototype同样带有_ proto _属性);
var arr = [1,2,3]
arr._proto_ == Array.prototype
每个对象的_ proto _ 等于这个对象的构造函数的prototype属性
上面的例子 arr 数组对象的构造函数就 是Array,所以他的_ proto _ 属性等于Array的prototype属性

构造函数

除了直接用{ … }创建一个对象外,js还可以用一种构造函数的方法来创建对象。它的用法是,先定义一个构造函数:

function Student(name) {    this.name = name;    this.hello = function () {        alert('Hello, ' + this.name + '!');    }}

构造函数跟普通函数区别在于 构造函数可以用关键字new来调用并返回一个对象

var robert = new Student('robert')
xiaoming.constructor === Student.prototype.constructor; // trueStudent.prototype.constructor === Student; // true

构造函数的constructor 指向自己

Javascript还提供了一个instanceof运算符,验证原型对象与实例对象之间的关系
alert(robert instanceof Student); //true

构造函数方法很好用,但是存在一个浪费内存的问题,每次生成一个对象都会生成一次属性和方法
怎么能让某些属性和方法在内存中只生成一次?
Prototype模式

function Student(props) {    this.name = props.name || '匿名'; // 默认值为'匿名'    this.grade = props.grade || 1; // 默认值为1}Student.prototype.hello = function () { // 公用函数    alert('Hello, ' + this.name + '!');};

函数继承

"动物"对象的构造函数function Animal(){  this.yyy= "动物";}'dog'对象构造函数function dog(name,color){   this.name = name;   this.color = color;}

1.使用call或apply方法(构造函数模式)

function dog(name,color){    Animal.apply(this, arguments);    this.name = name;    this.color = color;}var dog1= new dog("a毛","yellow");alert(dog1.yyy); // 动物

弊端:无法达到函数的复用,优势:每个对象相互不影响
2.prototype模式

function Animal(){ }  Animal.prototype.species = "动物";
dog.prototype = Animal.prototype;dog.prototype.constructor = Cat;var dog1 = new dog("大毛","黄色");alert(dog1.species); // 动物

弊端:任何对dog.prototype的修改,都会反映到Animal.prototype。

组合继承(王道)

function SuperType(name){  this.name = name;  this.colors = ["red", "blue", "green"];}SuperType.prototype.sayName = function(){   alert(this.name);};function SubType(name, age){//继承属性  SuperType.call(this, name);  this.age = age;}//继承方法SubType.prototype = new SuperType();SubType.prototype.constructor = SubType;SubType.prototype.sayAge = function(){alert(this.age);};

组合继承避免了原型链和借用构造函数的缺陷,融合了它们的优点,成为JavaScript 中最常用的继承模式

原创粉丝点击