重学前端是程劭非(winter)在极客时间开的一个专栏,在此主要整理个人学习笔记。若有侵权,请联系我,谢谢。前端
js提供内置函数,来访问和操纵原型bash
var cat = {
say(){
console.log("meow~");
},
jump(){
console.log("jump");
}
}
var tiger = Object.create(cat, {
say:{
writable:true,
configurable:true,
enumerable:true,
value:function(){
console.log("roar!");
}
}
})
var anotherCat = Object.create(cat);
anotherCat.say();
var anotherTiger = Object.create(tiger);
anotherTiger.say();
复制代码
(待补充)函数
new运算一个构造器和一组参数,实际作了这三件事学习
new操做让函数对象在语法上跟类类似,可是,它提供了两种方式,一种是在构造器添加属性,一种是经过构造器的prototype属性添加属性ui
// 经过构造器
function c1(){
this.p1 = 1;
this.p2 = function(){
console.log(this.p1);
}
}
var o1 = new c1;
o1.p2();
// 经过构造器的原型
function c2(){
}
c2.prototype.p1 = 1;
c2.prototype.p2 = function(){
console.log(this.p1);
}
var o2 = new c2;
o2.p2();
复制代码
用new来实现一个Object。create的不完整polyfillthis
Object.create = function(prototype){
var cls = function(){}
cls.prototype = prototype;
return new cls;
}
复制代码
这段代码建立了一个空函数做为类,并把传入的原型挂在了它的prototype,最后建立了一个它的实例,根据 new 的的行为,这将产生一个以传入的第一个参数为原型的对象。spa
类的基本写法prototype
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea();
}
// Method
calcArea() {
return this.height * this.width;
}
}
复制代码
经过get/set来建立getter,经过括号和大括号来建立方法,数据型成员写在构造器里。设计
类提供了继承能力code
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
class Dog extends Animal {
constructor(name) {
super(name); // call the super class constructor and pass in the name parameter
}
speak() {
console.log(this.name + ' barks.');
}
}
let d = new Dog('Mitzie');
d.speak(); // Mitzie barks.
复制代码
比起早期的原型模拟方式,使用 extends 关键字自动设置了 constructor,而且会自动调用父类的构造函数,这是一种更少坑的设计。