类是用于创建对象的模板。他们用代码封装数据以便更好的处理该数据(简单的说ES6的类就是语法糖)。 JS中的类是建立在原型上,
class的本质: 其实还是一个函数
<script>
class Person {
}
console.log(typeof Person); //function
</script>
上面打印出function 既类的本质其实还是一个函数 我们也可以简单的认为类就是构造函数的另外一种写法
但是ES6 之前通过 构造函数和原型实现面向对象编程
ES5写法:
<script>
function Person(name,age){
this.name=name;
this.age= age;
Person.prototype.sayHello=function(){
console.log('Hello,my name is ' +this.name);
}
}
var p1=new Person('张三',20)
var p2=new Person(' 李思',19)
p1.sayHello();
console.log(p1);
console.log(p1.__proto__ === Person.prototype); //true
</script>
但现在利用ES6 class 编程时:
<script>
class Person {
}
console.log(typeof Person); //function
console.log(Person.prototype); //object
console.log(Person.prototype.constructor); // class Person{}
Person.prototype.sing = function() { //原型对象添加方法
console.log('');
}
var p1= new Person();
console.dir(p1);
console.log(p1.__proto__ === Person.prototype); //true
</script>
-
类有原型对象prototype
-
类原型对象prototype 里面有constructor 指向类本身
-
类创建的实例对象有__proto__ 原型指向 类的原型对象
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。