JavaScript constructors, prototypes, and the `new` keyword
Are you baffled(阻碍;使迷惑) by the new operator in JavaScript? Wonder what the difference between a function and a constructor is? Or what the heck a prototype is used for?
I’m going to lay it out straight.
Now, there’s been a lot of talk for a long time about so-called “pseudo-classical” JavaScript. Mostly, the new guard of JavaScript folk don’t like to use the new keyword. It was written into the language to act more like Java, and its use is a little confusing. I’m not going to take sides here. I’m just going to explain how it works. It’s a tool; use it if it’s practical.
WHAT IS A CONSTRUCTOR?
A constructor is any function which is used as a constructor. The language doesn’t make a distinction. A function can be written to be used as a constructor or to be called as a normal function, or to be used either way.
A constructor is used with the new keyword:
var Vehicle = function Vehicle() {
// ...
}
var vehicle = new Vehicle();
WHAT HAPPENS WHEN A CONSTRUCTOR IS CALLED?
When new Vehicle() is called, JavaScript does four things:
- It creates a new object.
- It sets the
constructorproperty of the object toVehicle. - It sets up the object to delegate to
Vehicle.prototype. - It calls
Vehicle()in the context of the new object.
The result of new Vehicle() is this new object.
1. IT CREATES THE NEW OBJECT.
This is nothing special, just a fresh, new object: {}.
2. IT SETS THE CONSTRUCTOR PROPERTY OF THE OBJECT TO VEHICLE.
This means two things:
vehicle.constructor == Vehicle // true
vehicle instanceof Vehicle // true
This isn’t an ordinary property. It won’t show up if you enumerate the properties of the object. Also, you can try to set constructor, but you’ll just set a normal property on top of this special one. To wit:
vehicle; // {}
var FuzzyBear = function FuzzyBear() { };
vehicle.constructor = FuzzyBear;
vehicle; // { constructor: function FuzzyBear() }
vehicle.constructor == FuzzyBear; // true
vehicle instanceof FuzzyBear // false
vehicle instanceof Vehicle // true
The underlying, built in constructor property is something you can’t set manually. It can only be set for you, as part of construction with the new keyword.
为了避免很多新手忘记使用new关键字,所以会提供工厂方法,但是这个时候就必须担心类型比较的问题:
<script type="text/javascript">
function Foo() {
}
var foo = new Foo();
console.log(foo instanceof Foo);//true function Foo2(){
function InnerFoo2(){ }
return new InnerFoo2();
}
var foo2 = new Foo2();
console.log(foo2 instanceof Foo2);//false function Foo4(){}
function Foo3(){
function InnerFoo3(){ }
// InnerFoo3.prototype.constructor = Foo3;
return new InnerFoo3();
}
var foo3 = new Foo3();
console.log(foo3 instanceof Foo3);//false
console.log(foo3.constructor);//true function Foo4(){}
function Foo5(){
function InnerFoo5(){ }
InnerFoo5.prototype = new Foo4();
return new InnerFoo5();
}
var foo5 = new Foo5();
console.log(foo5 instanceof Foo4);//true
</script>
3. IT SETS UP THE OBJECT TO DELEGATE TO VEHICLE.PROTOTYPE.
Now it gets interesting.
A function is just a special kind of object, and like any object a function can have properties. Functions automatically get a property called prototype, which is just an empty object. This object gets some special treatment.
When an object is constructed, it inherits all of the properties of its constructor’s prototype. I know, it’s a brainful. Here.
Vehicle.prototype.wheelCount = 4;
var vehicle = new Vehicle;
vehicle.wheelCount; //
The Vehicle instance picked up the wheelCount from Vehicle‘s prototype
Now this “inheritance” is more than simply copying properties to the new objects. The object is set up to delegate any properties which haven’t been explicitly set up to its constructor’s prototype. That means that we can change the prototype later, and still see the changes in the instance.
Vehicle.prototype.wheelCount = 6;
vehicle.wheelCount; //
But if we like, we can always override it.
vehicle.wheelCount = 8;
vehicle.wheelCount //
(new Vehicle()).wheelCount // 6;
We can do the same thing with methods. After all, a method is just a function assigned to a property. Check it.
Vehicle.prototype.go = function go() { return "Vroom!" };
vehicle.go(); // "Vroom!"
4. IT CALLS VEHICLE() IN THE CONTEXT OF THE NEW OBJECT.
Finally, the constructor function itself is called. Inside the function, this is set to the object we’re constructing. (Why? Because that’s what Java does.) So,
var Vehicle = function Vehicle(color) {
this.constructor; // function Vehicle()
this.color = color;
}
(new Vehicle("tan")).color; // "tan"
Side note: Above, I said the use of the
newkeyword returned the constructed object. This is correct unless the constructor returns something explicitly. Then that object is returned, and the constructed object is just dropped. But really. JavaScript slaves over a hot CPU to create this object for you and then you just throw it away? Rude. And confusing to people who use your constructor. So unless you have a really good reason, don’t return anything from constructor functions.
PUTTING IT ALL TOGETHER
Given this tool, here’s one way (the intended way, but not the only way) to implement something like classes in JavaScript.
// Class definition / constructor
var Vehicle = function Vehicle(color) {
// Initialization
this.color = color;
} // Instance methods
Vehicle.prototype = {
go: function go() {
return "Vroom!";
}
}
“SUBCLASSING”
This “pseudoclassical” style doesn’t have an exact way to make subclasses, but it comes close. We can set the prototype of our “subclass” to an instance of the “superclass”.
var Car = function Car() {};
Car.prototype = new Vehicle("tan");
Car.prototype.honk = function honk() { return "BEEP!" };
var car = new Car();
car.honk(); // "BEEP!"
car.go(); // "Vroom!"
car.color; // "tan"
car instanceof Car; // true
car instanceof Vehicle; // true
Now, there’s a problem here. The Vehicle constructor only gets called once, to set up Car‘s prototype. We need to give it a color there. We can’t make different cars have different colors, which is not ideal. Some JavaScript frameworks have gotten around this by defining their own implementations of classes.
AND FOR MY LAST TRICK…
Sometimes you don’t want a notion of classes. Sometimes you just want one object to inherit the properties of another (but be able to override them). This is how most prototype-based languages work, but not JavaScript. At least, not without a little massaging.
This function lets us accomplish it. It’s been tossed around for a long time and is sometimes called “create” and sometimes “clone” and sometimes other things.
function create(parent) {
var F = function() {};
F.prototype = parent;
return new F();
}
var masterObject = {a: "masterObject value"}
var object1 = create(masterObject);
var object2 = create(masterObject);
var object3 = create(masterObject);
var object3.a = "overridden value";
object1.a; // "masterObject value"
object2.a; // "masterObject value"
object3.a; // "overridden value"
masterObject.a = "new masterObject value"
object1.a; // "new masterObject value"
object2.a; // "new masterObject value"
object3.a; // "overridden value"
YOU SAID A MOUTHFUL.
The JavaScript prototype chain is a little different than how most languages work, so it can be tricky understand. It doesn’t make it any easier when JavaScript gets syntax that makes it looks more like other languages, like inheriting Java’s new operator. But if you know what you’re doing, you can do some crazy-cool things with it.
<script type="text/javascript">
function Father(){
this.name = 'father name';
}
Father.prototype.get_name = function(){
return this.name;
}
function Son(){ }
Son.prototype = new Father();
var son = new Son();
son.name = 'son name';
console.log(son.get_name());//测试一下覆盖了父类的属性之后的表现
delete son.name
console.log(son.get_name()); </script>
JavaScript constructors, prototypes, and the `new` keyword的更多相关文章
- JavaScript Constructors
Understanding JavaScript Constructors It was: 1) This article is technically sound. JavaScript doesn ...
- 图解Javascript原型链
本文尝试阐述Js中原型(prototype).原型链(prototype chain)等概念及其作用机制.上一篇文章(图解Javascript上下文与作用域)介绍了Js中变量作用域的相关概念,实际上关 ...
- [Javascript] ES6 Class Constructors and the Super Keyword
When the ES6 class shipped back in 2015, a number of additional keywords came with it. Two of these ...
- [Javascript] The "this" keyword
The very first thing to understand when we're talking about this-keyword is really understand what's ...
- javascript 私有方法的实现
原文地址: http://frugalcoder.us/post/2010/02/11/js-classes.aspx Classy JavaScript - Best Practices 11. F ...
- You Don't Know JS: this & Object Prototypes (第6章 Behavior Delegation)附加的ES6 class未读
本章深挖原型机制. [[Prototype]]比类更直接和简单! https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%2 ...
- A re-introduction to JavaScript (JS Tutorial) 转载自:https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
A re-introduction to JavaScript (JS Tutorial) Redirected from https://developer.mozilla.org/en-US/do ...
- 我也谈javascript闭包
1.什么是闭包呢?Whenever you see the function keyword within another function, the inner function has acces ...
- How do JavaScript closures work?
Like the old Albert Einstein said: If you can't explain it to a six-year-old, you really don't under ...
随机推荐
- collectionView布局原理及瀑布流布局方式--备用
最近学习到了瀑布流的实现方法,瀑布流的实现方式有多种,这里应用collectionView来重写其UICollectionViewLayout进行布局是最为简单方便的.但再用其布局之前必须了解其布局原 ...
- 触发UIButton长按事件
UIButton *aBtn=[UIButton buttonWithType:UIButtonTypeCustom]; [aBtn setFrame:CGRectMake(40, 100, 60, ...
- C# const和statci readonly区别
1.const 是属于编译时的变量,它定义的常量是在对象初始化时赋值,以后不能改变他的值. 它适用于两种场景:1.取值永久不变(比如圆周率.一天包含的小时数.地球的半径等) 2.对程序性能要求非常苛 ...
- Codeforces Round #359 div2
Problem_A(CodeForces 686A): 题意: \[ 有n个输入, +\space d_i代表冰淇淋数目增加d_i个, -\space d_i表示某个孩纸需要d_i个, 如果你现在手里 ...
- CSS3画三角形原理
1.首先看一下画出一个下三角形完整的代码及效果图 #trangle1-up{ width:; height:; border-left:50px solid transparent; border-r ...
- Fckeditor漏洞利用总结
查看编辑器版本FCKeditor/_whatsnew.html——————————————————————————————————————————————————————— —————— 2. Ver ...
- Java 开发者不容错过的 12 种高效工具
Java 开发者常常都会想办法如何更快地编写 Java 代码,让编程变得更加轻松.目前,市面上涌现出越来越多的高效编程工具.所以,以下总结了一系列工具列表,其中包含了大多数开发人员已经使用.正在使用或 ...
- Cassandra查询语言CQL的基本使用
在window环境下运行CQL语言要先安装python环境,在linux下不需要,cassandra内置了python. 1.查看python版本:python --version2.运行pythod ...
- javascript模板引擎Mustache
Mustache(英文本意:触须,胡须)是基于JavaScript实现的模版引擎,类似于JQuery Template,但是这个模版更加的轻量级,语法更加的简单易用,很容易上手. 下载:https:/ ...
- BZOJ_1012_[JSOI2008]_最大数maxnumber_(线段树/树状数组+RMQ)
描述 http://www.lydsy.com/JudgeOnline/problem.php?id=1012 两种操作: 1.求序列末尾n个数中的最大值. 2.在序列末尾插入一个数. 分析 线段树求 ...