从构造函数中引用Javascript实例变量而不使用'this'关键字

Referring Javascript Instance Variable from Constructor without using 'this' keyword

本文关键字:关键字 this 构造函数 引用 Javascript 变量 实例      更新时间:2023-09-26

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

        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
        }`

"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;
            };
        }

并使用'methods':

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

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

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

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');
在你的代码末尾有一个}',一定要把它改成};

请参阅jsbin..https://jsbin.com/teyupuhele/edit?html、js、输出

这是面向对象的最佳实践…

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