gpt4 book ai didi

javascript - 什么是 javascript 中的代理原型(prototype)交换?

转载 作者:可可西里 更新时间:2023-11-01 01:57:49 25 4
gpt4 key购买 nike

underscore.js code ,评论状态:

// Naked function reference for surrogate-prototype-swapping.
var Ctor = function(){};
  • 什么是代理原型(prototype)交换?

  • 我在哪里可以找到关于代理原型(prototype)交换的文章/清晰的文档?

最佳答案

通过 Blender 实现的回答。适用于与我同级别的人。

虽然它不是一个真正的术语,但以下是通过对原始 underscore.js 的更完整评论对代理原型(prototype)交换的预期含义的分割。代码。

// A function which will be used as a constructor function in order 
// to add a prototype to a new object. There is nothing special about
// this function, except how it will be used.
var Ctor = function(){};

// Create a shortcut to Object.create if it exists. Otherwise
// nativeCreate will be undefined
var nativeCreate = Object.create;

// An internal function that will use or act as a polyfill for
// Object.create, with some type checking built in.
var baseCreate = function(prototype) {
// Check if the object passed to baseCreate is actually an object.
// Otherwise simply return an object (from an object literal),
// because there is not a valid object to inherit from.
if (!_.isObject(prototype)) return {};

// If Object.create is implemented then return the value
// returned by Object.create when the prototype parameter is
// passed into it. If Object.create has already been
// implemented there is no need to recreate it. Just return
// its return value.
if (nativeCreate) return nativeCreate(prototype);

// If Object.create is not defined then Ctor comes into play.
// The object passed to baseCreate is assigned to the prototype
// of Ctor. This means when Ctor is called prototype will be
// the prototype assigned to this (the keyword this).
Ctor.prototype = prototype;
// Because Ctor is called with the new keyword this (the
// keyword this) is returned returned by Ctor. Thus, the
// variable 'result' is assigned an object with a prototype
// equal to baseCreate's parameter 'prototype'.
var result = new Ctor;
// Then to reset things Ctor.prototype is set to null.
Ctor.prototype = null;
// The newly created object, whose prototype is the object
// passed to baseCreate is returned.
return result;
};

关于javascript - 什么是 javascript 中的代理原型(prototype)交换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30496650/

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