码迷,mamicode.com
首页 > 其他好文 > 详细

class和构造函数

时间:2019-03-01 18:25:54      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:UNC   es5   tostring   返回   mamicode   string   构造函数   方法   poi   

技术图片

 

/*ES6class*/
/*class实际是构造函数语法糖,是对构造函数的一层包装,是为了容易理解*/
/*class与构造函数共同点:所有的方法都在原型上*/
class Point1 {
  count=6 /*属于实列的属性,不在原型上,不会被继承*/
  constructor(x, y) {
    this.x = x; /*this指向实例对象,x,y在对象自身,不在原型上*/
    this.y = y;
  }

  toString() {
    return ‘(‘ + this.x + ‘, ‘ + this.y + ‘)‘;
  }
}
var p1 = new Point1(1, 2);
console.log("class====",p1)
console.log(Object.keys(Point1.prototype))
/*ES5构造函数*/
//不同点class里面的不可以枚举,es5中除去构造函数,其他都可以枚举
function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function () {
  return ‘(‘ + this.x + ‘, ‘ + this.y + ‘)‘;
};

var p = new Point(1, 2);
console.log("es5===",p)
console.log(Object.keys(Point.prototype))

new 做的事情

1.先创建一个对象

2.将目前作用域赋值给这个对象,即this指向当前对象

3.执行构造函数

4.返回一个对象。如果构造函数没有返回对象的情况下,就返回当前对象

class和构造函数

标签:UNC   es5   tostring   返回   mamicode   string   构造函数   方法   poi   

原文地址:https://www.cnblogs.com/sisi2020/p/10457992.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!