js中的面向对象程序设计

概述

面向对象的语言有一个标志,那就是他们都有类的概念,而通过类可以创建任意多个具有相同属性和方法的对象。


对象的创建

1、工厂模式

//工厂模式
    function getPerson(name,age){
        //定义age不能直接访问
        var person = {
            name:name,
            _age:age,
            getName:function(){
                return this.name;
            }
        };
        Object.defineProperties(person,{
            _age:{
                value:age
            },
            age:{
                get:function(){
                    return this._age;
                },
                set:function(age){
                    this._age = age;
                }
            }

        });
        return person;
    }
        var p2 = getPerson("person2",12);
        console.log(p2.getName());
2、构造函数模式

 //构造函数模式
    function Person(name,age){
        this.name = name;
        this.age = age;
        this.getName = getName;
    }
    var p1 = new Person("person1",12);
    console.log(p1.getName());
3、原型模式

//原型模式
    function People(){};
    People.prototype = {
        name:"",
        age:0,
        getName:getName
    }
        var p3 = new People();
        p3.age = 12;
        p3.name="person3";
        console.log(p3.getName());
        console.log("sex" in p3);
4、构造函数+原型

//*构造函数+原型模式*//
    function Student(name,age){
        this.name = name;
        this.age = age;
    }
    Student.prototype ={
        constructor:Student,
        getName:getName
    }
var stu = new Student("student",18);
        console.log(stu.getName());

传播GIS知识 | 交流GIS经验 | 分享GIS价值 | 专注GIS发展

技术博客

http://blog.csdn.net/gisshixisheng


在线教程

http://edu.csdn.net/course/detail/799

Github

https://github.com/lzugis/


联系方式

q       q:1004740957

e-mail:niujp08@qq.com

公众号:lzugis15

Q Q 群:452117357(webgis)
             337469080(Android)







原文地址:https://www.cnblogs.com/lzugis/p/6539782.html