我读了一本名为"面向Web开发人员的专业Javascript"的书,它说:"变量由参考值或原始值指定.参考值是存储在内存中的对象".然后它没有说明如何存储原始值.所以我猜它没有存储在内存中.基于此,当我有这样的脚本:
var foo = 123;
Run Code Online (Sandbox Code Playgroud)
Javascript如何记住foo变量供以后使用?
我从一本书中得到了这个练习(没有解决方案):
想象一下String()构造函数不存在.创建一个构造函数MyString(),它尽可能地像String()一样工作.您不能使用任何内置字符串方法或属性,并且请记住String()不存在.您可以使用此代码来测试构造函数:
Run Code Online (Sandbox Code Playgroud)>>> var s = new MyString('hello'); >>> s.length;
然而,我有一个解决方案,但不确定我是否遵循了要求(即:"我不允许使用任何内置的字符串方法或属性"); 这是我的解决方案:
function MyString(string) {
this.length = 0;
for(var i in string) {
this.length++;
}
}
var x = new MyString("Hello");
x.length;
Run Code Online (Sandbox Code Playgroud)
我不确定的是for-in循环.你能告诉我那个循环中字符串变量的数据类型是什么吗?是那种数组还是我用它作为字符串(这是我确实打破了要求)?非常感谢!
我在javascript中创建了这段代码:
function Shape() {}
Shape.prototype.name = "Shape";
Shape.prototype.toString = function() {
result = [];
if(this.constructor.uber) {
result[result.length] = this.constructor.uber.toString();
}
result[result.length] = this.name;
return result.join(', ');
}
function twoDShape() {};
twoDShape.prototype = new Shape();
twoDShape.prototype.constructor = twoDShape;
twoDShape.uber = twoDShape.prototype;
twoDShape.name = "twoD Shape";
var a = new twoDShape();
console.log(a.toString());
Run Code Online (Sandbox Code Playgroud)
我不知道为什么但是当我运行它时,firefox就冻结了.我一直在努力解决这个问题.我的猜测是我的代码中应该有一个无限循环,并且它存在于if条件的某个地方,但我没有找到它.有人可以帮我解决这个问题.谢谢!
javascript ×3