gpt4 book ai didi

javascript - 尝试在javascript中模拟类,但无法访问内部变量

转载 作者:行者123 更新时间:2023-11-28 08:01:01 25 4
gpt4 key购买 nike

我正在生成很多“类”(实际上是尝试模拟 C# 或其他面向对象语言中的类的函数),并且正在寻找实现此目的的最佳方法。您可能会注意到,我还提供了 jQuery。

这是此时生成所有类的方式:

MyClass = (function() {
function innerClass() {

var self = this;
var myField;

// This function works as the constructor
this.init = function(opts) {
// Arguments to the constructor
var defaultOpts = {
myInitArgument: null
}
opts = $.extend(defaultOpts, opts);
self = this;

// Any custom constructor code is generated here...
}

// A function
this.myFunction = function() {
myField = "Hello World!";
}

// Returns an object with all selected fields and function that should work as "public". Those not mentioned here, will not be visible outside this class.
return {
init: this.init,
myFunction: this.myFunction,
myField: myField,
}
}
return innerClass;
})();

然后我创建该类的实例,如下所示:

var myObject = new MyClass();
myObject.init({myInitArgument: 'test'});

我的主要问题是在 myFunction 内部,“myField”将设置为“Hello World!”如果我中断调试器(即 Chrome 开发人员工具),但使用“myObject.myField”返回未定义。

我做了一个fiddle如果您想尝试一下这个示例。

解决这个问题的最佳方法是什么?您是否还有其他需要警告我的事情?

最佳答案

JavaScript 在创建类和对象时有点奇怪。 IMO,这是最可靠、最易读的方法:从成为原始对象(Fruit)的函数开始。

编辑:感谢@Bergi指出以前的版本有残余变量,需要移至init()。

function Fruit(opts) {
this.init(opts);
}

现在,扩展该函数,为其提供更多功能,例如 init 等:

Fruit.prototype.init = function(opts) {
// init values go here
this.cost = 0;
this.count = 0;

var that = this; // in the iteration below, we want to refer to our parent
for( k in opts )(function(k, v) {
that[k] = v;
})(k, opts[k]);
}

// now, here's a specialized set of functions that sets properties (price/quant)
// note that they do "return this" - this is so you can conveniently chain
// commands. ex: apple.setPrice(10).setQuantity(5);
Fruit.prototype.setPrice = function(how_much) {
this.cost = how_much;
return(this);
}

Fruit.prototype.setQuantity = function(how_many) {
this.count = how_many;
return(this);
}

返回计算值的简单函数。此时,一旦实例化,对象就会变得“ self 意识”。像这样的辅助函数变得更具可读性。

Fruit.prototype.getEarnings = function() {
return( this.cost * this.count );
}

到目前为止,我们只设置了抽象结构。要使用它,请创建一个新对象:

var apple = new Fruit({ genus: 'Malus' });
var orange = new Fruit({ genus: 'Citrus' });

apple.setPrice(1.50).setQuantity(20);
orange.setPrice(1.25).setQuantity(40);

console.info( apple.genus + " will earn you $" + apple.getEarnings() ); // $30
console.info( orange.genus + " will earn you $" + orange.getEarnings() ); // $50

关于javascript - 尝试在javascript中模拟类,但无法访问内部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25383417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com