问题1: OOP 指什么?有哪些特性
Object Oriented Programing,即面向对象程序设计,其中两个最重要的概念就是类和对象,类只是具备了某些功能和属性的抽象模型,而实际应用中需要一个一个实体,也就是需要对类进行实例化,类在实例化之后就是对象。
- 特性
继承性:子类自动继承其父级类中的属性和方法,并可以添加新的属性和方法或者对部分属性和方法进行重写。继承增加了代码的可重用性。
多态性:子类继承了来自父类中的属性和方法,并对其中部分方法进行重写。
封装性:将一个类的使用和实现分开,只保留部分接口和方法与外部联系。
问题2: 如何通过构造函数的方式创建一个拥有属性和方法的对象?
可通过如下的代码来创建:
Function Person(name,age){
this.name = name
this.age = age
}
Person.prototype.sayName = function(){
console.log('I am ' + this.name)
}
问题3: prototype 是什么?有什么特性
1.在JavaScript中,每个函数都有prototype这个属性,对应的值是原型对象
2.每个对象都有内部属性proto,这个属性指向其构造函数的prototype原型对象
问题4:画出如下代码的原型图
function People (name){
this.name = name;
this.sayName = function(){
console.log('my name is:' + this.name);
}
}
People.prototype.walk = function(){
console.log(this.name + ' is walking');
}
var p1 = new People('饥人谷');
var p2 = new People('前端');

原型链图
问题5: 创建一个 Car 对象,拥有属性name、color、status;拥有方法run,stop,getStatus
Function Car(name,color,status){
this.name = name
this.color = color
this.status = status
}
Car.prototype.run = function(){
console.log(this.name + 'is running')
}
Car.prototype.getStatus = function(){
console.log(this.status)
}
问题6: 创建一个 GoTop 对象,当 new 一个 GotTop 对象则会在页面上创建一个回到顶部的元素,点击页面滚动到顶部。拥有以下属性和方法
-
ct属性,GoTop 对应的 DOM 元素的容器 -
target属性, GoTop 对应的 DOM 元素 -
bindEvent方法, 用于绑定事件 -
createNode方法, 用于在容器内创建节点
function GoTop(ct){
this.ct = ct
this.createNode()
this.bindEvent()
}
GoTop.prototype.bindEvent = function(){
this.target.addEventListener('click',function(){
document.body.scrollTop = 0
})
}
GoTop.prototype.createNode = function(){
this.target = document.createElement('div')
this.target.innerText = 'GoTop'
this.target.style.position = 'fixed'
this.target.style.bottom = '20px'
this.target.style.right = '100px'
this.target.style.padding = '10px'
this.target.style.color = 'white'
this.target.style.borderWidth = '2px'
this.target.style.borderColor = 'white'
this.target.style.borderStyle = 'solid'
this.target.style.cursor = 'pointer'
this.ct.append(this.target)
}
new GoTop(document.body)