前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >js中的面向对象程序设计

js中的面向对象程序设计

作者头像
lzugis
发布2018-10-23 12:01:10
5770
发布2018-10-23 12:01:10
举报

概述

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

对象的创建

1、工厂模式

代码语言:javascript
复制
//工厂模式
    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、构造函数模式

代码语言:javascript
复制
 //构造函数模式
    function Person(name,age){
        this.name = name;
        this.age = age;
        this.getName = getName;
    }
    var p1 = new Person("person1",12);
    console.log(p1.getName());

3、原型模式

代码语言:javascript
复制
//原型模式
    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、构造函数+原型

代码语言:javascript
复制
//*构造函数+原型模式*//
    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());
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年06月23日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档