zoukankan      html  css  js  c++  java
  • JS 面向对象

    摘自:廖雪峰老师的JS教程

    简介

    JavaScript不区分类和实例的概念,而是通过原型(prototype)来实现面向对象编程
    这是与其他编程语言的区别(比如Java)

    创建对象

    JavaScript对每个创建的对象都会设置一个原型,指向它的原型对象。

    逐层查找

    当我们用obj.xxx访问一个对象的属性时,JavaScript引擎先在当前对象上查找该属性,如果没有找到,就到其原型对象上找,如果还没有找到,就一直上溯到Object.prototype对象,最后,如果还没有找到,就只能返回undefined

    例如,创建一个Array对象:

    var arr = [1, 2, 3];
    

    其原型链是:

    arr ----> Array.prototype ----> Object.prototype ----> null
    

    Array.prototype定义了indexOf()shift()等方法,因此你可以在所有的Array对象上直接调用这些方法。

    函数的原型链

    当我们创建一个函数时:

    function foo() {
        return 0;
    }
    

    函数也是一个对象,它的原型链是:

    foo ----> Function.prototype ----> Object.prototype ----> null
    

    由于Function.prototype定义了apply()等方法,因此,所有函数都可以调用apply()方法。

    很容易想到,如果原型链很长,那么访问一个对象的属性就会因为花更多的时间查找而变得更慢,因此要注意不要把原型链搞得太长

    构造函数

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

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

    这确实是一个普通函数,但是在JavaScript中,可以用关键字new来调用这个函数,并返回一个对象

    var xiaoming = new Student('小明');
    xiaoming.name; // '小明'
    xiaoming.hello(); // Hello, 小明!
    

    注意:如果不写new,这就是一个普通函数,它返回undefined。但是,如果写了new,它就变成了一个构造函数,它绑定的this指向新创建的对象,并默认返回this,也就是说,不需要在最后写return this;

    新创建的xiaoming的原型链是:

    xiaoming ----> Student.prototype ----> Object.prototype ----> null
    

    也就是说,xiaoming的原型指向函数Student的原型。如果你又创建了xiaohongxiaojun,那么这些对象的原型与xiaoming是一样的:

    xiaoming ↘
    xiaohong -→ Student.prototype ----> Object.prototype ----> null
    xiaojun  ↗
    

    new Student()创建的对象还从原型上获得了一个constructor属性,它指向函数Student本身:

    xiaoming.constructor === Student.prototype.constructor; // true
    Student.prototype.constructor === Student; // true
    
    Object.getPrototypeOf(xiaoming) === Student.prototype; // true
    
    xiaoming instanceof Student; // true
    

    在这里插入图片描述
    红色箭头是原型链。注意,Student.prototype指向的对象就是xiaomingxiaohong的原型对象,这个原型对象自己还有个属性constructor,指向Student函数本身。

    另外,函数Student恰好有个属性prototype指向xiaomingxiaohong的原型对象,但是xiaomingxiaohong这些对象可没有prototype这个属性,不过可以用__proto__这个非标准用法来查看。

    对象__proto__属性的值就是它所对应的原型对象:
    详情查阅:https://www.jianshu.com/p/184d325e34a6

    var a = {x: 1};
    var b = new Object();
    a.__proto__ === Object.prototype // true
    b.__proto__ === Object.prototype // true
    one.toString === one.__proto__.toString // true
    

    对象都有__proto__属性来标识自己所继承的原型,只有函数才有prototype属性。

    现在我们就认为xiaomingxiaohong这些对象“继承”自Student

    不过还有一个小问题,注意观察:

    xiaoming.name; // '小明'
    xiaohong.name; // '小红'
    xiaoming.hello; // function: Student.hello()
    xiaohong.hello; // function: Student.hello()
    xiaoming.hello === xiaohong.hello; // false
    

    xiaomingxiaohong各自的name不同,这是对的,否则我们无法区分谁是谁了。

    xiaomingxiaohong各自的hello是一个函数,但它们是两个不同的函数,虽然函数名称和代码都是相同的!

    如果我们通过new Student()创建了很多对象,这些对象的hello函数实际上只需要共享同一个函数就可以了,这样可以节省很多内存。

    要让创建的对象共享一个hello函数,根据对象的属性查找原则,我们只要把hello函数移动到xiaomingxiaohong这些对象共同的原型上就可以了,也就是Student.prototype
    在这里插入图片描述
    修改代码如下:

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

    小结

    不要忘记写new,另外构造函数一般首字母大写,方便编译器识别提示。
    最后,我们还可以编写一个createStudent()函数,在内部封装所有的new操作。一个常用的编程模式像这样:

    function Student(props) {
        this.name = props.name || '匿名'; // 默认值为'匿名'
        this.grade = props.grade || 1; // 默认值为1
    }
    
    Student.prototype.hello = function () {
        alert('Hello, ' + this.name + '!');
    };
    
    function createStudent(props) {
        return new Student(props || {})
    }
    
    我的实验
    <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<title>JavaScript测试</title>
    		<script type="text/javascript">
    			'use strict';
    			function Person(name,age){
    				this.name=name;
    				this.age=age;
    				Person.prototype.eat=function(){
    					alert(this.name+'今年'+this.age+'岁了!');
    					var that=this;//解决this undefined
    					(function(){console.log(that.name);})();
    				}
    				
    			}
    			var a=new Person('小明',23);
    			var b=new Person('小红',20);
    			a.eat();
    			b.eat();
    			console.log(a.eat===b.eat);//true
    		</script>
    	</head>
    	<body>
    		
    	</body>
    </html>
    
    
  • 相关阅读:
    Scrapy学习篇(九)之文件与图片下载
    Scrapy学习篇(八)之settings
    SQL拾遗
    SQL命令导入导出
    Spring Security构建Rest服务-1401-权限表达式
    Spring Security构建Rest服务-1400-授权
    Spring Security构建Rest服务-1300-Spring Security OAuth开发APP认证框架之JWT实现单点登录
    Spring Security构建Rest服务-1205-Spring Security OAuth开发APP认证框架之Token处理
    Spring Security构建Rest服务-1204-Spring Security OAuth开发APP认证框架之Token处理
    Spring Security构建Rest服务-1203-Spring Security OAuth开发APP认证框架之短信验证码登录
  • 原文地址:https://www.cnblogs.com/tfxz/p/13251777.html
Copyright © 2011-2022 走看看