做开发几年,js定义“类”的方式一直是funtion,现在也有了class,看了几篇文章,大致了解了一下class的用法,其实大致和funtion差不多,细节上会有些区别和完善。之前定义构造函数,我们会这样写。
<script> function Person(name, age, sex){ this.name = name; this.age = age; this.sex = sex; } Person.prototype.say = function (){ console.log(`${this.name} can say words`) } var people = new Person('xinxin',29,'man') people.say() </script>
之前我们会一些对象的属性写在函数体内,对于一些方法,我们会写在原型上,这样一来可以节省内存,对于每个实例来说,属性可能是必须得,方法共用原型链的就行。
那如果现在用class改写这段代码。
<script> class Person { constructor (name, age, sex){ this.name = name; this.age = age; this.sex = sex; } say (){ console.log(`${this.name} can say words`) } } var people = new Person('xinxin2', 29, 'man'); people.say() </script>
这样就实现了这个函数。那我们看下两个类实例化出来的对象是什么样子的。
<script> function Person(name, age, sex){ this.name = name; this.age = age; this.sex = sex; } Person.prototype.say = function (){ console.log(`${this.name} can say words`) } var people = new Person('xinxin',29,'man') console.log('fun======', people) class Person1 { constructor (name, age, sex){ this.name = name; this.age = age; this.sex = sex; } say (){ console.log(`${this.name} can say words`) } } var people = new Person1('xinxin2', 29, 'man'); console.log('class===', people) </script>
可以看到,class内部的方法相当于是function上的原型链继承,之后会分享一些class独有的,function没有的特性。
文章来源:
前端这点事
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
还木有评论哦,快来抢沙发吧~