关于组合与继承在线有很多信息,但我还没有找到适合JavaScript的例子.使用以下代码演示继承:
function Stock( /* object with stock names and prices */ ) {
for (var company_name in arguments[0]) {
// copy the passed object into the new object created by the constructor
this[company_name] = arguments[0][company_name];
}
}
// example methods in prototype, their implementation is probably redundant for
// this question, but list() returns an array with toString() invoked; total()
// adds up the stock prices and returns them. Using ES5 feature to make
// inherited properties non-enumerable
Stock.prototype = …
Run Code Online (Sandbox Code Playgroud) 告诉我,如果我错了:
原型是普通对象.当一个对象继承原型时,它不仅仅复制原型的属性,该对象存储对原型的引用.
在Firefox中,我可以这样做:
var food = {fruit:"apple"};
var more_food = {vegetable:"celery"};
food.__proto__ = more_food;
food.vegetable // celery
food.fruit // apple
Run Code Online (Sandbox Code Playgroud)
我可以使用该__proto__
属性手动设置对原型对象的引用.
我也可以用Object.create
:
var food = {fruit:"apple"};
var more_food = {vegetable:"celery"};
food = Object.create(more_food);
food.vegetable // celery
food.fruit // undefined
Run Code Online (Sandbox Code Playgroud)
究竟在Object.create
做什么?变量食物是否分配了对原型more_food的引用,或者是Object.create只返回对象的副本more_food?如果Object.create
只是制作副本,那么如果变量食物没有引用more_food,原型链如何工作?
我不明白Perl中的自动增量字母.
这个例子似乎完全可以理解:
$a = 'bz'; ++$a;
ca #output
Run Code Online (Sandbox Code Playgroud)
b
增加到c
.没有什么z
可去的,所以它可以追溯到a
(或至少这是我看到的过程).
但后来我遇到这样的陈述:
$a = 'Zz'; ++$a;
AAa #output
Run Code Online (Sandbox Code Playgroud)
和:
$a = '9z'; ++$a;
10 #output
Run Code Online (Sandbox Code Playgroud)
为什么不增加Zz
收益Aa
?为什么不增加9z
回报0z
呢?
谢谢!
标量上下文中的列表赋值返回右侧的元素数:
scalar(my ($hello, $there, $world) = (7,8)); #evaluates to 2
Run Code Online (Sandbox Code Playgroud)
为什么它评估右侧并生成2,而不是新定义的列表被评估并返回3?
对我来说,似乎$hello
得到7,$there
得到8,$world
得到undef
,然后该列表在标量上下文中进行评估,这将导致3,因为这是列表中元素的数量($hello $there $world
).对我来说,上下文会影响返回计算表达式的哪一部分,这似乎很奇怪:
my $greeting = (($hello, $there, $world) = (7,8)); #2
my @greeting = (($hello, $there, $world) = (7,8));
my $greeting_length = @greeting; #3
Run Code Online (Sandbox Code Playgroud) 我正在阅读"Beginning Perl"一书,它给出了这两个陈述:
print "Test one: ", 6 > 3 && 3 > 4, "\n";
print "Test two: ", 6 > 3 and 3 > 4, "\n";
Run Code Online (Sandbox Code Playgroud)
第一行没有打印任何新行,第二行打印1没有新行.
我对输出感到困惑.根据作者的说法,第二个语句给出了奇怪的输出,因为它就像是说:
print ("Test two: ", 6 > 3) and 3 > 4, "\n";
Run Code Online (Sandbox Code Playgroud)
但是,为什么第一个陈述不一样?我认为它与print的优先级有关.&&具有比打印更高的优先级,因此首先进行评估然后打印.而"和"的优先级低于打印,因此将打印6> 3,打印返回1,然后使用"和"进行评估.然而,这并没有多大意义.
我已经阅读了关于列表运算符的优先级如何工作的Perl文档,但我仍然不理解这个例子.你们可以剖析这两个陈述,告诉我先打印什么吗?您是否也可以解释Perl文档在提到列表操作符为"向左"和"向右"时的含义?谢谢.
非常感谢大家的回答.我现在明白了.我确实在做cjm所说的,并且认为有左右列表操作符.所以现在我明白了它的含义,我理解了整个事情.