面向对象的特征1、第一个特征:封装1.1概念:隐藏实现细节的过程1.2优点:重用和隐藏细节Java里面有权限修饰符,但是JS里面没有,JS所有的属性都是公共的,为了让属性私有化,就有相应方法:第一种:定义一个私有变量,结合get/set函数function Student(name,age,phone){ ???this.name = name;//公共属性 ???this.age = age;//公共属性 ???let _phone = phone;//私有属性 ???this.setPhone = function(phone){ ???????console.log("1"); ???????_phone = phone;//设置私有属性 ???} ???this.getPhone = function(){ ???????console.log("2"); ???????return _phone;//获取私有属性 ???}}let s1 = new Student("关羽",19,322);s1.setPhone(123);//修改私有属性,因为调用了setPhone函数此时会输出1console.log(s1.name,s1.age,s1.getPhone()); //因为调用了getPhone函数,会先输出2,再输出关羽 19 123 第二种 defineProperty方法function Teacher(name,age,hoby){this.name = name;this.age = age;this.hoby = hoby;}Object.defineProperty(Teacher.prototype,"name",{set:function(name){ ???_name = name;},get:function(){ ???if (this.age > 30) { ???????return "大龄" + _name; ???} ???return _name;}})let T1 = new Teacher("张飞",32,"游泳");console.log(T1.name,T1.age,T1.hoby);//输出 ?大龄张飞 ?32 ?游泳
JS中对象的特征:封装(函数)
原文地址:https://www.cnblogs.com/cj-18/p/9164608.html