Home>Article>Web Front-end> Not to be missed: From prototype to prototype chain, cultivate JavaScript internal skills
Write at the end
(Free learning recommendation:javascript video tutorial)
Preface
It's time to look back on the past again. Knowledge is like this. Prototypes and prototype chains were rarely used in my previous internship career - almost none (poof! I'm showing off my cards), but it and this point to the problem Likewise, it is a topic that junior and intermediate front-end developers can never avoid during interviews. Does everyone search for knowledge points related to prototypes every time they read the interview?
Look at this knowledge, you can only know its importance during the exam. It’s like a sincere interview question was once placed in front of me... The topic is brought back, and we will accept this todayevil creature!
1. Constructor
The constructor itself is a function, no different from an ordinary function, butgenerally capitalizes its first letterfor the sake of standardization. The difference between a constructor and an ordinary function is that the function that usesnewto generate an instance is a constructor, and the function that is called directly is an ordinary function.
function Person() { this.name = 'yuguang';};var person = new Person();console.log(person.name) // yuguang
In this example, Person is a constructor.
constructor
Returns a reference to the constructor function when creating the instance object. The value of this property is a reference to the function itself, rather than a string containing the function name.
You can see that the constructor of the instance object points to its constructor, and its relationship with the prototype will be linked together later.
constructor
?In JavaScript, every object with aprototypeautomatically gets the constructor property. Except:arguments
,Enumerator
,Error
,Global
,Math
,RegExp
, etc. Except for some special objects, all other built-in JavaScript objects have a constructor attribute. For example:Array
,Boolean
,Date
,Function
,Number
,Object
,String
etc. All major browsers support this attribute. Open the console and we can verify it
// 字符串console.log('str'.constructor) // ƒ String() { [native code] }console.log('str'.constructor === String) // true// 数组console.log([1,2,3].constructor) // ƒ Array() { [native code] }console.log([1,2,3].constructor === Array) // true// 数字var num = 1console.log(num.constructor) // ƒ Number() { [native code] }console.log(num.constructor === Number) // true// Dateconsole.log(new Date().constructor) // ƒ Date() { [native code] }// 注意!!!不要混淆哦console.log(new Date().getTime().constructor) // ƒ Number() { [native code] }// Booleanconsole.log(true.constructor) // ƒ Boolean() { [native code] }console.log(true.constructor === Boolean) // true// 自定义函数function show(){ console.log('yuguang');};console.log(show.constructor) // ƒ Function() { [native code] }// 自定义构造函数,无返回值function Person(){ this.name = name;};var p = new Person()console.log(p.constructor) // ƒ Person()// 有返回值function Person(){ this.name = name; return { name: 'yuguang' }};var p = Person()console.log(p1.constructor) // ƒ Object() { [native code] }
Since the difference between the constructor and the ordinary function is only in the calling method, we should understand new.
new
operator is called, the function will always return an object;The code is as follows:
通常情况下var MyClass = function(){ this.name = 'yuguang';};var obj = new MyClass();obj.name; // yuguang特殊情况var MyClass = function(){ this.name = 'yuguang'; return { name: '老王' }};var obj = new MyClass();obj.name // 老王
We use the__proto__
(implicit prototype, will be mentioned below) attribute to simulate the process of new calling the constructor :
var objectNew = function(){ // 从object.prototype上克隆一个空的对象 var obj = new Object(); // 取得外部传入的构造器,这里是Person var Constructor = [].shift.call( arguments ); // 更新,指向正确的原型 obj.__proto__ = Constructor.prototype; //知识点,要考、要考、要考 // 借用外部传入的构造器给obj设置属性 var ret = Constructor.apply(obj, arguments); // 确保构造器总是返回一个对象 return typeof ref === 'object' ? ret : obj;}
2. Prototype
JavaScript is a The prototype-based language imitates Java's two type mechanisms when designing:Basic type
andObject type
. It can be seen that prototypes are very important!
Each object has a prototype object, and classes are defined in the form of functions. Prototype represents the prototype of the function and also represents a collection of members of a class. Look at the picture below:
You can find the prototype of the Person function itself:
(Person.prototype.constructor => Person )
(We call it implicit prototype)
这是每一个JavaScript对象(除了 null )都具有的一个属性,叫__proto__
,这是一个访问器属性(即 getter 函数和 setter 函数),通过它可以访问到对象的内部[[Prototype]]
(一个对象或 null )。
function Person() {}var person = new Person();console.log(person.__proto__ === Person.prototype); // true
于是我们更新下关系图:
小结:每个引用类型的隐式原型都指向它的构造函数的显式原型
前文提到了constructor
,它与原型的关系也可以添加到这张图里,更新下关系图:
根据上图的关系,下面这段的结果,大家就一目了然了:
function Person() {}var person = new Person();console.log(person.__proto__ == Person.prototype) // trueconsole.log(Person.prototype.constructor == Person) // true// 顺便学习一个ES5的方法,可以获得对象的原型console.log(Object.getPrototypeOf(person) === Person.prototype) // true
接下来我们要继续思考实例和原型的关系:
三、实例与原型
当读取实例的属性时,如果找不到,就会查找与对象关联的原型中的属性,如果还查不到,就去找原型的原型,一直找到最顶层为止。这样一个查找过程
举个例子:
function Person() {}Person.prototype.name = '老王';var person = new Person();person.name = '余光';console.log(person.name) // 余光delete person.name;console.log(person.name) // 老王
在这个例子中,我们给实例对象 person 添加了 name 属性,当我们打印 person.name 的时候,结果自然为 余光(is me)。
描述:
但是当我们删除了 person 的 name 属性后,再次读取 person.name,从 person 对象中找不到 name 属性就会从 person 的原型也就是 person.proto,也就是 Person.prototype中查找,幸运的是我们找到了 name 属性,结果为 老王(这…)
总结:
实例a
中的所有属性,但没有找到目标属性;name
属性的这个请求被委托给该实例a
的构造器(A
)的原型,它被a.__proto__
记录着并且指向A.prototype;但是万一还没有找到呢?原型的原型又是什么呢?
四、原型的原型
在前面,我们已经讲了原型也是一个对象,既然是对象,我们就可以用最原始的方式创建它,那就是:
var obj = new Object();obj.name = '余光'console.log(obj.name) // 余光
其实原型对象就是通过Object
构造函数生成的,结合之前所讲,实例的__proto__
指向构造函数的prototype
,可以理解成,Object.prototype()
是所有对象的根对象,所以我们再次更新下关系图:
五、原型链
每个对象拥有一个原型对象,通过__proto__
指针指向上一个原型 ,并从中继承方法和属性,同时原型对象也可能拥有原型,这样一层一层,最终指向null
。这种关系被称为原型链(prototype chain),通过原型链一个对象会拥有定义在其他对象中的属性和方法。
这个链条存在着终点,是因为:Object.prototype 的原型是——null,引用阮一峰老师的 《undefined与null的区别》 就是:
null 表示“没有对象”,即该处不应该有值。这句话也意味着 Object.prototype 没有原型
我们最后更新一次关系图,蓝色线条就可以表示原型链这种关系。
1.constructor
首先是 constructor 属性,我们看个例子:
function Person() {}var person = new Person();console.log(person.constructor === Person); // true
当获取 person.constructor 时,其实 person 中并没有 constructor 属性,当不能读取到constructor 属性时,会从 person 的原型也就是 Person.prototype 中读取,正好原型中有该属性,所以:
person.constructor === Person.prototype.constructor
2.__proto__
其次是proto,绝大部分浏览器都支持这个非标准的方法访问原型,然而它并不存在于 Person.prototype 中,实际上,它是来自于 Object.prototype ,与其说是一个属性,不如说是一个 getter/setter,当使用 obj.proto时,可以理解成返回了 Object.getPrototypeOf(obj)。
3.真的是继承吗?
最后是关于继承,前面我们讲到“每一个对象都会从原型‘继承’属性”,实际上,继承是一个十分具有迷惑性的说法,引用《你不知道的JavaScript》中的话,就是:
Inheritance means copying. However, JavaScript does not copy the properties of an object by default. Instead, JavaScript just creates an association between two objects, so that one object can access the properties and functions of another object through delegation. , so instead of calling it inheritance,Delegationis more accurate.
6. Summary
The prototype chain has an end point and will not be searched indefinitely;
Related free learning recommendations:javascript(Video)
The above is the detailed content of Not to be missed: From prototype to prototype chain, cultivate JavaScript internal skills. For more information, please follow other related articles on the PHP Chinese website!