zoukankan      html  css  js  c++  java
  • ECMAScript 面向对象技术:创建你自己的对象

    在javascript中创建新的对象有几种方法:

    1. 直接创建一个对象的实例

    下面的代码创建了一个新的实例,然后添加了四个属性:

    personObj=new Object();
    personObj.firstname="John";
    personObj.lastname="Doe";
    personObj.age=50;
    personObj.eyecolor="blue"; 

    或者你也可以这样直接创建一个实例

     personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};

    给personObj添加一个方法也很简单.下面的代码给personObj添加了一个eat()方法

    personObj.eat=eat;

    eat = function() {

      //do something 

    2. 创建一个构造器

    创建一个function生成对象

    function person(firstname,lastname,age,eyecolor)
    {
    this.firstname=firstname;
    this.lastname=lastname;
    this.age=age;
    this.eyecolor=eyecolor;
    }

    在function内部你需要指定赋值给属性名,使用this给所有属性的原因是因为你将一次有多个person实例(你要处理哪个person必须清楚)。this就是当前正在处理person的实例。

    一旦你有对象构造器,你可以创建新的对象实例,像这样 

    var myFather=new person("John","Doe",50,"blue");
    var myMother=new person("Sally","Rally",48,"green");

    你也可以添加一些方法给这个对象构造器,你一样可以在function内部完成 

    function person(firstname,lastname,age,eyecolor) 

    {
    this.firstname=firstname;
    this.lastname=lastname;
    this.age=age;
    this.eyecolor=eyecolor;

    this.newlastname=newlastname;
    }

    注意这些方法仅仅是附加到objects上的,我们需要实现这个newlastname() 方法;

    function newlastname(new_lastname)
    {
    this.lastname=new_lastname;
    }
    newlastname() 方法定义了person's 新的last name 和指定给这个person。 通过this关键字,javascript知道你要指定给哪个person。现在你可以这样写

    myMother.newlastname("Doe") 

    假如你现在想在你的对象构造器中添加另一个方法,你又不想改变上面的代码,你可以这样做

     person.prototype.eat = function() {  

      //do somethng

    }

  • 相关阅读:
    linux 常用命令(个人记录)
    jmeter 5.0版本更新说明(个人做个记录)
    Netdata---Linux系统性能实时监控平台部署记录
    MySQL Yum存储库 安装、升级、集群
    linux 各项配置汇总
    构建Maven项目自动下载jar包
    计算服务器的pv量算法
    性能计算公式
    jstack(查看线程)、jmap(查看内存)和jstat(性能分析)命令
    结构模式
  • 原文地址:https://www.cnblogs.com/az19870227/p/2279762.html
Copyright © 2011-2022 走看看