小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
构造函数和原型
ES6之前创建对象
1.var Star = new Object()
2.var Star = {}
3.构造函数创建对象
function Star(names,age) {
this.names = names
this.age = age
this.sing = function() {
console.log('hello');
}
}
var ns = new Star('liu', 20);
ns.sing()
静态成员和实例成员
构造函数中的属性和方法称为成员 1、实例成员是实例化对象中的 2、在构造函数本身上直接添加的属性或者方法,只能通过构造函数来访问
function Star(names,age) {
this.names = names
this.age = age
this.sing = function() {
console.log('hello');
}
}
var ns = new Star('liu', 20);
console.log(ns.age);
Star.color = 'yellow';
console.log(ns.color);
console.log(Star.color);
原型
构造函数虽然好用,但容易造成内存浪费,特别是类中有方法的时候
解决方案;构造函数原型prototype
系统自动给对象添加对象原型__proto__指向prototype
用处:prototype定义对象方法,使实例化对象可以共享;函数里面写公共属性
function star{
constructor(usname){
this.usname = usname;
}
sing(){
console.log(this.usname);
}
}
let ldh = new star('hello')
console.dir(ldh);
对象方法通常这样写
star.prototype.sing() = function(){
console.log('hello');
}
constructor函数指向构造函数本身,记录该对象引用哪个构造函数,是__proto__、prototype的一个属性,有一个原型链,js对成员查找就是沿着原型链,本身找不到就去原型对象中找 一般情况this指向调用者; 通过原型对象扩展内置对象的方法
继承
1、call()改变函数中this的指向
function fn(){
console.log('hello world');
console.log(this);
}
let s = {
name:'yello',
age:20
}
fn.call(s);
借构造函数继承属性
function Father(umane,ages){
this.uname = umane,
this.age = ages
}
function Son(a,b){
Father.call(this,a,b)
}
let sons = new Son(19,20);
console.log(sons);
借用原型对象继承方法
function Father(umane,ages){
this.uname = umane,
this.age = ages
}
function Son(a,b){
Father.call(this,a,b)
}
Father.prototype.mony = function (){
console.log('make money');
}
Son.prototype = new Father();
Son.prototype.mi = function(){
console.log('mi');
}
Son.prototype.constructor = Son;
let sons = new Son(19,20);
console.log(Father.prototype);
console.log(Son.prototype);