1、目前在 JavaScript 中使用最广泛、认同度最高的一种创建自定义类型的方法
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.friends = ["ZhangSan", "LiSi"];
}
Person.prototype = {
constructor : Person,
sayName : function(){
console.log(this.name);
}
}
var person1 = new Person("Stone", 28, "Software Engineer");
var person2 = new Person("Sophie", 29, "English Teacher");
person1.friends.push("WangWu");
console.log(person1.friends); // "ZhangSan,LiSi,WangWu"
console.log(person2.friends); // "ZhangSan,LiSi"
console.log(person1.friends === person2.friends); // false
console.log(person1.sayName === person2.sayName); // true
2、new创造对象的方法等同于
//构造函数的原型(prototype)与实例的原型(_proto_)
function Person(){}
var person = new Person();
console.log(person.__proto__ === Person.prototype); // true
//另一种创造构造函数的方法
function Person(){}
var person = new Person();
// 上一行代码等同于以下过程 ==>
var person = {};
person.__proto__ = Person.prototype;
Person.call(person); //以 person 为作用域执行了 Person 函数
3、ES6的类
//ES5写法
//构造函数
function Point(x, y) {
this.x = x;
this.y = y;
}
//在原型上定义一个toString方法
Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
};
//实例化
var p = new Point(1, 2);
p.x //1
p.y //2
p.toString() //"(1+2)"
//ES6的语法糖
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
//全部定义在原型链上
class Point {
constructor() {}
toString() {}
toValue() {}
}
// 等同于
Point.prototype = {
constructor() {},
toString() {},
toValue() {},
};
js模式
1、工厂模式
function createPerson(name, age, job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
return o;
}
2、构造函数
方法私有
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = function(){
alert(this.name);
};
}
3、原型
方法共享
对象字面量创造原型
constructor 属性不再指向 Person
constructor : Person,
function Person(){}
Person.prototype = {
//特意加上
constructor : Person,
name : "Nicholas",
age : 29,
job: "Software Engineer",
sayName : function () {
alert(this.name);
}
};
4、原型加构造函数组合
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Shelby", "Court"];
}
Person.prototype = {
constructor : Person,
sayName : function(){
alert(this.name);
}
}
5、类的一些特性
静态方法
class Foo {
static classMethod() {
return 'hello';
}
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod() // TypeError: foo.classMethod is not a function
// 可以被子类继承
class Bar extends Foo {}
Bar.classMethod() // 'hello'
6、类的继承
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y); // 调用父类的constructor(x, y)
this.color = color;
}
toString() {
return this.color + ' ' + super.toString(); // 调用父类的toString()
}
}
tips: react在除了constructor之外的生命周期已经传入了this.props了,完全不受super(props)的影响。
网友评论