Skip to content

Instantly share code, notes, and snippets.

@rankun203
Created September 13, 2013 02:02
Show Gist options
  • Save rankun203/6546083 to your computer and use it in GitHub Desktop.
Save rankun203/6546083 to your computer and use it in GitHub Desktop.
利用中间对象避免修改子类prototype时自动修改父类的prototype,实现继承。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript Test</title>
</head>
<body>
</body>
</html>
<script>
function extend (child, parent) {
var F = function () {};
F.prototype = parent.prototype;
child.prototype = F.prototype;
child.prototype.constructor = child;
}
function Animal () {};
Animal.prototype.specis = "动物";
function Cat (name) {
this.name = name;
function getName () {
return this.name;
}
}
extend(Cat, Animal);
var cat1 = new Cat("金猫");
var cat2 = new Cat("银猫");
console.log(cat1.name + " is a " + cat1.specis);
console.log(cat2.name + " is a " + cat2.specis);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment