<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> function Person() { this.name="cyg"; this.setAge=function(myAge) { if(myAge>=0) { age=myAge; } } this.getAge=function() { return age; } this.say=function() { console.log("666"); } } let obj = new Person(); obj.setAge(-3);//记住,如果没有age这个属性的话,就添加。 /*obj.age=-3;//给没有这个属性age的对象设置age属性,并赋值.\ console.log(obj.age); 条件:该作用域没有该属性,想给属性赋值的情况下 */ console.log(obj.getAge()); // 1.操作的是私有属性(局部变量) /*obj.age=-3;//给没有这个属性age的对象设置age属性,并赋值.\ console.log(obj.age);*/ </script> </body> </html>
JS中私有属性注意点
关注
打赏