简体   繁体   English

为什么push方法适用于对象?

[英]Why push method works on with object?

Why does "push method" works with object? 为什么“推送方法”适用于对象? How that mechanism works underhood? 该机制如何在内部运作?

function MyArray() { }
MyArray.prototype = [];

var arr = new MyArray();
arr.push(1, 2, 3);
console.log(arr); // [1, 2, 3]  in Chrome

在此处输入图片说明

sorry for my english. 对不起我的英语不好。 Thanks! 谢谢!

MyArray returns an object, even in Chrome, and uses the methods of Array , via assigned prototypal inheritance . MyArray即使在Chrome中也返回一个对象,并通过分配的原型继承使用Array的方法。 The result of an instance of MyArray is still an object, not an array. MyArray实例的结果仍然是对象,而不是数组。

 function MyArray() { } MyArray.prototype = []; var arr = new MyArray(); arr.push(1, 2, 3); console.log(arr); // { 0: 1, 1: 2, 2: 3, length: 3 } console.log(typeof arr); // object console.log(Array.isArray(arr)); // false console.log(arr instanceof Array); // true console.log(arr instanceof MyArray); // true 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM