// Objects with prototype are plain iff they were constructed by a global Object function
Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; //这行是什么意思?
return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
The following are the codes mentioned in the appeal code
var class2type = {};
var toString = class2type.toString;
var getProto = Object.getPrototypeOf;
var hasOwn = class2type.hasOwnProperty;
var fnToString = hasOwn.toString;
var ObjectFunctionString = fnToString.call( Object );
var proto, Ctor;
proto = getProto( obj );
In jQuery 3.2.1, the last two lines of the function that determines whether an object is a pure object are not equivalent when I tested it myself. I would like to ask what the problem is
var obj = function(){};
var proto = Object.getPrototypeOf(obj);
var Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
var objHasOwn = Object.hasOwnProperty.toString.call( Object );
var funcHasOwn = Object.hasOwnProperty.toString.call( Ctor );
console.log(funcHasOwn === objHasOwn); // 我使用纯 function 来测试,发现结果是 false
Ask me
Why the output is false
Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
What does it mean
Object.hasOwnProperty.toString.call( Object )
The output is function Object() { [native code] }
Object.hasOwnProperty. toString.call(Number)
The output isfunction Number() { [native code] }
why
巴扎黑2017-06-12 09:30:36
// 判断参数是不是纯粹的对象 通过{}、new Object()、Object.create(null)
isPlainObject: function( obj ) {
var proto, Ctor;
// 借用toString方法判断obj的类型是不是Object
if ( !obj || toString.call( obj ) !== "[object Object]" ) {
return false;
}
// 获取对象的原型
proto = getProto( obj );
// 通过Object.create( null )创建的对象返回true
if ( !proto ) {
return true;
}
// 判断对象是不是通过new Object()方式创建的
Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
// fnToString:将函数转换成字符串 ObjectFunctionString:function Object() { [native code] }
return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
}
1. var obj = function(){}; returns false because you have misunderstood the function of this function. It does not mean to create it through a function, it means new Object();
Object.hasOwnProperty.toString.call(Number) output is function Number() { [native code] } because Object.hasOwnProperty.toString will return the object's constructor function in string form, and the call method borrows from Object.hasOwnProperty toString method.