Skip to content

一道题测js水平

LYF edited this page Aug 14, 2017 · 5 revisions
function Parent () {
    this.a = 1
    this.b = [1, 2, this.a]
    this.c = { demo : 5 }
    this.show = function () {
        console.log(this.a, this.b, this.c.demo)
    }
}

function Child () {
    this.a = 2
    this.change = function () {
        this.b.push(this.a)
        this.a = this.b.length
        this.c.demo = this.a++
    }
}

Child.prototype = new Parent()

var parent = new Parent()
var child1 = new Child()
var child2 = new Child()


child1.a = 11
child2.a = 12
parent.show() // 1, [1,2,1], 5
child1.show() // 11, [1,2,1], 5
child2.show() // 12, [1,2,1], 5
child1.change() // p:b = [1,2,1,11], c1:a = 4, p:c = {demo:4}, c1:a = 5
child2.change() // p:b = [1,2,1,11,12], c1:a = 5, p:c = {demo:5}, c1:a = 6
parent.show() // 1, [1,2,1], 6 // 这个是最容易迷惑的,因为parent对象是已经创建好了的,在创建好之后,其内部数据已经确定child1\2并不会影响parent对象
child1.show() // 5, [1,2,1,11,12], 5
child2.show() // 6, [1,2,1,11,12], 5

得出的结论:

  1. 原型上的方法内的this其实还是调用者对象,而不是原型对象;
  2. this在运行期绑定的;属性是静态绑定的;
Clone this wiki locally