recherche

Maison  >  Questions et réponses  >  le corps du texte

javascript - 简单的JS面向对象编程问题:怎么封装私有属性,并暴露公有方法?

想把JS代码封装成面向对象的方式
把敏感信息封装成私有属性,并暴露公有的方法给人调用
但发现调用的时候都没反应……求大神指点一下

1

2

3

4

5

6

7

8

9

10

11

12

13

<code>    //封装了Person对象

    var Person = (function(){

        var name = "william"//私有属性名字

        return {

            //公有方法

            sayHi : function(){

                alert("hello my name's "+ this.name);

            }

        }

    })();

     

    //调用

    Person.sayHi();    </code>

阿神阿神2882 Il y a quelques jours715

répondre à tous(3)je répondrai

  • 阿神

    阿神2017-04-11 12:07:59

    1

    <code> alert("hello my name's "+ this.name);</code>

    此时的this作用域为sayHi所在的对象,而你这个对象是没有name属性的,如果要暴露出来,请改为

    1

    <code> alert("hello my name's "+ name);</code>

    répondre
    0
  • 黄舟

    黄舟2017-04-11 12:07:59

    问题的根源在于this指向

    répondre
    0
  • PHP中文网

    PHP中文网2017-04-11 12:07:59

    JavaScript没有真正意义上的面向对象,deepcopy对象的性能损失严重,真正能做到私有封装的只有闭包。

    répondre
    0
  • Annulerrépondre