美文网首页
JS--面向对象学习第一天

JS--面向对象学习第一天

作者: 桐谷杰人 | 来源:发表于2017-08-15 21:38 被阅读0次

    一、面向对象的属性:property

    1.用来储存数据field(域),字段,属性

    2.用来表示行为方法

    注:访问对象的属性的时候,可以使用[],就像使用下标去数组中的元素一样。[变量]

    eg.console.log(p["name"]);

    二、对象的属性,可以动态的增加和删除

    1.delect删除对象属性

    2.添加到window中的属性,不能删除,即变量不能删除

    三、在对象的方法中使用this时,this代表调用这个方法的时候使用的那一个对象,工厂方法创建对像的方法有,一,通过字面量获取对像,二、工厂方法

    四、js函数的参数的传递:永远的值传递

    五、可以使用for...in来遍历对象的所有属性

    六、使用构造函数创建对像,必须使用关键字new,后面跟着构造函数的名,根据需要传入相应的参数。当构造函数的作用域赋给新对象时,意味着这个时候this就代表了这个对象。

    练习一、

    设计一个构造函数, 利用这个构造函数可以创建对象, 每个对象表示平面上的一个点, 每个对象应该提供一个方法: 功能是, 可以计算这个点和其他点之间的距离。

    function Point(x, y){

    this.x = x;

    this.y = y;

    this.distance = function (other){

    return Math.sqrt((this.x - other.x) * (this.x - other.x)

    + (this.y - other.y) * (this.y - other.y))

    }

    }

    var p1 = new Point(10, 20);

    var p2 = new Point(20, 30);

    console.log(p1);

    console.log(p2);

    console.log(p1.distance(p2));

    console.log(p2.distance(p1));

    练习二、

    设计一个构造函数, 表示平面上的一个圆. 提供两个方法: 一个计算这个圆的周长, 一个计算这个圆的面积再增加一个功能, 可以计算两个圆的圆心之间的距离

    function yuan(x,y,r){

    this.x=x;

    this.y=y;

    this.r=r;

    this.distance = function(other){

    return Math.sqrt((this.x-other.x)*(this.x-other.x)+(this.y-other.y)*(this.y-other.y))

    }

    this.perimeter=function (){

    return Math.PI*this.r*2;

    }

    this.area=function(){

    return Math.PI*this.r*this.r;

    }

    }

    var y1=new yuan(10,30,5);

    var y2=new yuan(10,10,20);

    console.log(y1.distance(y2));

    console.log(y1.perimeter(),y1.area());

    console.log(y2.perimeter(),y2.area());

    相关文章

      网友评论

          本文标题:JS--面向对象学习第一天

          本文链接:https://www.haomeiwen.com/subject/jqevrxtx.html