大家好,又见面了,我是你们的朋友全栈君。
1 . JavaScript原型 如果所有对象都有私有字段[[prototype]],就是对象的原型; 读一个属性,如果对象本身没有,则会继续访问对象的原型,直到原型为空或者找到为止。
操作原型的三种方法:
Object.create 根据指定的原型创建新对象,原型可以是 null;
Object.getPrototypeOf 获得一个对象的原型;
Object.setPrototypeOf 设置一个对象的原型。
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运算接收一个构造器和一组调用参数:
以构造器的 prototype 属性(注意与私有字段[[prototype]]的区分)为原型,创建新对象;
将 this 和调用参数传给构造器,执行;
如果构造器返回的是对象,则返回,否则返回第一步创建的对象。
用构造器模拟类的两种方法( 旧版本 ):
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();
第一种方法是直接在构造器中修改 this,给 this 添加属性。
第二种方法是修改构造器的 prototype 属性指向的对象,它是从这个构造器构造出来的所有对象的原型。
ES6中的类 基本写法:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea();
}
// Method
calcArea() {
return this.height * this.width;
}
}
类的继承:
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.
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/163391.html原文链接:https://javaforall.cn