从Constructor引用Javascript实例变量,而不使用' this'关键词

时间:2015-07-30 10:30:43

标签: javascript oop

我刚开始使用JavaScript oops概念,我想从一个构造函数中访问3个实例变量,而不是这个'这个'关键字,第一个值即将到来,但不是第二个......等等......“

        function CreateObject()
        {
            var p1 = new person('chanky',25,'Male');           
        }

        function person(name,age,sex)
        {
            this.name = name; 
            this.age = age;
            this.sex = sex;      

            document.write(name); //Working
            document.write(age); //not Working
            document.write(sex); //not Working

         /*If we use 'this' keyword then all are Working */

            document.write(this.name); // Working
            document.write(this.age); // Working
            document.write(this.sex); // Working
        }`

3 个答案:

答案 0 :(得分:1)

'this'有什么问题?您想要访问未声明的成员,因此您使用“this”。

您可以像这样访问类外的值:

var p = new person('chanky',25,'Male');
alert (p.age);

function person(name,age,sex)
        {
            this.name = name; 
            this.age = age;
            this.sex = sex;      
        }

如果你仍然担心,声明一个变量并将你收到的值分配给它们,并且当你使用OO方法时,封装变量以便在你的类之外访问它们

function person(name,age,sex)
        {
            var _name;
            var _age;
            var _sex;

            _name = name; 
            _age = age;
            _sex = sex;      

            this.getName = function () {
                return _name;
            };

            this.getAge = function () {
                return _age;
            };

            this.getSex = function () {
                return _sex;
            };
        }

并使用'方法':

var p2 = new person('chanky',25,'Male');
alert (p2.getAge());

答案 1 :(得分:0)

请参阅jsbin .. https://jsbin.com/teyupuhele/edit?html,js,output

这是OOP的最佳做法......

function person(name, age, sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;


};

// create p1 instance of object person

var p1 = new person('chanky', 22, 'Male');

console.log(p1.name); //Working
console.log(p1.age); //Working
console.log(p1.sex); //Working

答案 2 :(得分:0)

你好Chanky这应该可以正常工作

我刚创建了一个使用console.log显示的jsFiddle

jsFiddle:https://jsfiddle.net/hq4ebs2d/

Javascript

function person(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;

    console.log(name); //Working
    console.log(age); //not Working
    console.log(sex); //not Working

    /*If we use 'this' keyword then all are Working */

    console.log(this.name); // Working
    console.log(this.age); // Working
    console.log(this.sex); // Working
};

var p1 = new person('chanky', 25, 'Male');

在代码末尾只有一个快速注释},请确保将其更改为};