我最近Object.create()在JavaScript中偶然发现了这个方法,并试图推断它与创建一个对象的新实例有什么不同new SomeFunction(),当你想要使用另一个时.
请考虑以下示例:
var test = {
val: 1,
func: function() {
return this.val;
}
};
var testA = Object.create(test);
testA.val = 2;
console.log(test.func()); // 1
console.log(testA.func()); // 2
console.log('other test');
var otherTest = function() {
this.val = 1;
this.func = function() {
return this.val;
};
};
var otherTestA = new otherTest();
var otherTestB = new otherTest();
otherTestB.val = 2;
console.log(otherTestA.val); // 1
console.log(otherTestB.val); // 2
console.log(otherTestA.func()); // 1
console.log(otherTestB.func()); // 2Run Code Online (Sandbox Code Playgroud)
请注意,在两种情况下都观察到相同的行为.在我看来,这两种情况之间的主要区别是:
Object.create()实际使用的对象实际上形成了新对象的原型,而在new …关于这个脚本的一行:
function Vehicle(hasEngine, hasWheels) {
this.hasEngine = hasEngine || false;
this.hasWheels = hasWheels || false;
}
function Car (make, model, hp) {
this.hp = hp;
this.make = make;
this.model = model;
}
Car.prototype = new Vehicle(true, true);
Car.prototype.constructor = Car;
Car.prototype.displaySpecs = function () {
console.log(this.make + ", " + this.model + ", " + this.hp + ", " + this.hasEngine + ", " + this.hasWheels);
}
var myAudi = new Car ("Audi", "A4", 150);
myAudi.displaySpecs(); // logs: Audi, A4, …Run Code Online (Sandbox Code Playgroud) 编辑:由于我的误解,这个问题被问到了.请谨慎行事,因为阅读它可能会浪费您的时间.
我想call并且apply会在给定一组参数的情况下执行函数,但是我的测试结果令人困惑.看我的测试代码:
window.z = 0;
(function(){++(window.z)}).call(this, 1, 2, 3)
Run Code Online (Sandbox Code Playgroud)
我希望z在执行后会是3.但是,z是1.
(function(){++(window.z)}).apply(this, [1, 2, 3])
Run Code Online (Sandbox Code Playgroud)
同样在这里.z == 1;
我也试过简单地记录输入参数:
var x = function(y){console.log(y);}
x.call(this, 1, 2, 3);
Run Code Online (Sandbox Code Playgroud)
结果?仅记录1.
我在这做错了什么?
(使用Firebug在Chrome和Firefox中测试过.)