当我在Java中查看代码示例时,我看到了一个奇怪的代码:
public class Application {
public static void main(String[] args) {
String[] x = {"A"};
String[] y = x;
x[0] = "B";
System.out.print(x[0] + " " + y[0]);
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白,为什么结果"B B"是正确的?当我创建并初始化数组x和y并且指定数组x的零元素等于B时,我认为答案必须是"B A".
在这段代码中
function report(message) {
console.log(message);
}
function makeLoggable(target) {
return new Proxy(target, {
get(target, property) {
report(`Reading ${property}`);
const param = target;
return param[property];
},
set(target, property, value) {
report(`Writing value ${value} to ${property}`);
const param = target;
return param[property] = value;
},
});
}
let ninja = { name: 'Jack' };
ninja = makeLoggable(ninja);
console.assert(ninja.name === 'Jack', 'Our ninja Jack');
ninja.status = '';
Run Code Online (Sandbox Code Playgroud)
我有两个问题:
1) 为什么如果我将最后一行的属性状态值设置为 0 或 ""(空字符串),我会收到错误消息
未捕获的类型错误:代理上的“设置”:陷阱返回属性“状态”(...)的假
2)在规范中说我应该返回一个布尔值。但就我而言,在 set() 方法中,我不返回任何布尔值。在那种情况下,为什么这段代码有效?
请向我解释为什么当我编译这段代码时结果为0?怎么会这样 ?
class Parentt {
int x = 0;
public void printX() {
System.out.println(x);
}
}
class Child1 extends Parentt {
int x = -1;
}
public class Foo {
public static void main(String[] args) {
new Child1().printX();
}
}
Run Code Online (Sandbox Code Playgroud)