gpt4 book ai didi

Javascript无需实例化即可访问原型(prototype)中的变量

转载 作者:行者123 更新时间:2023-12-02 18:30:06 25 4
gpt4 key购买 nike

在 javascript 类中访问变量而不实例化它是一种不好的做法吗?

例如:

var Test = function(){
this.tests.push("Something");
}
Test.prototype.tests = [];

var test = new Test();

console.log(Test.prototype.tests); //Is this okay to do? Obviously I can use test.test here, but this is a poor example of why I am wanting to do this; it merely shows my question.

我遇到过一个只有 id 的实例,我想使用该类为我获取其自身的正确实例,例如:Test.prototype.getByID(id); 但我想确保这样做是否正确。

最佳答案

您可以利用 JavaScript 中的闭包并执行类似以下操作 ( jsfiddle )。这样做的好处是使您的“测试列表”私有(private),因此它不会被弄乱,并且您不必访问确实感觉有点奇怪的原型(prototype):

var Test = (function() {
var tests = {};

var Test = function(id){
tests[id] = this;
this.id = id;
}

Test.getByID = function(id) {
return tests[id];
}

return Test;
}());

var test1 = new Test(1);
var test2 = new Test(2);

var test2_2 = Test.getByID(2);

alert( test1 === test2_2 );//should be false
alert( test2 === test2_2 );//should be true

关于Javascript无需实例化即可访问原型(prototype)中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17892318/

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