gpt4 book ai didi

Javascript - 新方法

转载 作者:行者123 更新时间:2023-11-29 19:21:00 25 4
gpt4 key购买 nike

如果有人能为我分解它,让我能理解它,我会非常感激。我知道它用于通过 apply 方法创建新对象。

Function.prototype.new = function () {
var args = arguments;
var constructor = this;

function Fake() {
constructor.apply(this, args)
};
Fake.prototype = constructor.prototype;
return new Fake;
};

最佳答案

基本上,new 函数用于从调用它的对象继承新创建对象的原型(prototype)方法。

// new function is defined on the Function prototype so,
// it can be called directly from any function
Function.prototype.new = function () {
// Caching the arguments array-like object
var args = arguments;

// this inside the new() refers to the function on which the `new` is called
var constructor = this;

// A fake constructor function/class
function Fake() {
// Calling the function with passing the context and the arguments
constructor.apply(this, args)
};

// Adding the prototype members of the function on which new is called
// On the new fake class
Fake.prototype = constructor.prototype;

// Retun new instance of the fake class
// Actually returning only the prototypes here
return new Fake;
};

关于Javascript - 新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33053708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com