在javascript中的新方法中使用构造函数中的privat-var

Using privat var from constructor in new method in javascript

本文关键字:构造函数 privat-var 新方法 javascript      更新时间:2023-09-26

我写了一个构造函数

function Human() { 
var legs = 2;
var iq = 100; 
}

然后我创建一个对象的实例

var Man = new Human();

并且想要添加一个新的方法

Man.getIQ = function() {
return iq - 10;
}

但我听说智商是不确定的。即使我使用this.iq。为什么对象范围内的var不能用于新方法?

变量legsiq模拟Human类的"私有"成员,因为它们仅在该闭包中可见(仅在Human函数中可见)
如果您想从该范围之外访问它们,则需要将它们绑定到this关键字(this.iq=100;),或者为每个私有成员实现getterssetters

function Human() { 
    var legs = 2;
    this.getLegs = function(){
        return legs;
    };
}

无论如何,这些只是冰山一角;我解释了它们,这样你就可以理解为什么你试图做的事情失败了
如果我正确理解你想做什么,那么用js编写ideea oop的正确方法应该是这样的:

function Human(){}
Human.prototype = {
    legs : 2,
    iq : 100
};  
function Woman(){}
Woman.prototype = new Human;
Woman.prototype.getIq = function(){
    return this.eq - 10;
};
var womanInstance = new Woman();
// needless to say that this line is both wrong and misogynistic
alert('a woman has an iq of ' + womanInstance.getIq());

对不起,如果我被冲昏头脑了,但有很多文章&关于javascript oop的博客(比如这篇),我建议您在遇到此类问题之前/期间阅读。