new
operatör iç [[Construct]]
yöntemini kullanır ve bu temelde şunları yapar: Bu durumda, new C
böyle simüle edilebilir
- ayarlar yeni bir yerel nesneyi başlatır Bu nesnenin iç
[[Prototype]]
, İşlev prototype
özelliğine işaret eder.
- işlevin
prototype
özelliği bir amacı, Object.prototype
yerine kullanılır (örneğin, bir sayı, String, Boolean, Tanımsız veya boş olarak ilkel değerleri) değilse.
- nesnesi oluşturduktan sonra, kendi
this
değeri olarak nesnesi temin etmek; işlevini çağırır.
- Çağrılan işlevin dönüş değeri ilkel ise, dahili olarak oluşturulan nesne döndürülür.
- Aksi takdirde, bir nesne döndürülürse, dahili olarak oluşturulan nesne kaybolur.
new
operatörün bu gibi ifade edilebilir etmez ne eşdeğer bir uygulama (ECMAScript 5 Object.create
yöntem mevcut olduğu varsayılarak): İlgili arasında
function NEW(f) {
var obj, ret, proto;
// Check if `f.prototype` is an object, not a primitive
proto = Object(f.prototype) === f.prototype ? f.prototype : Object.prototype;
// Create an object that inherits from `proto`
obj = Object.create(proto);
// Apply the function setting `obj` as the `this` value
ret = f.apply(obj, Array.prototype.slice.call(arguments, 1));
if (Object(ret) === ret) { // the result is an object?
return ret;
}
return obj;
}
// Example usage:
function Foo (arg) {
this.prop = arg;
}
Foo.prototype.inherited = 'baz';
var obj = NEW(Foo, 'bar');
obj.prop; // 'bar'
obj.inherited; // 'baz'
obj instanceof Foo // true
Türü: http://stackoverflow.com/questions/1646698/what-is-the-new-keyword-in-javascript – Ivan